Home > Blockchain >  applying css to adjacent element
applying css to adjacent element

Time:12-14

Hi guys what If I have a html elements like below

<div>
  <div>Name</div>
  <div><input type="text" >
  <div>Age</div>
  <div><input type="number" ></div>
  <div>address1</div>
  <div><input type="text"></div>
</div>

I want to change the previous elements of the elements that have .check css property. something like Name -> *Name with read color.

Is it possible in CSS? or Do I need to mix with JS?

Any Ideas or suggestions would be appreciated.

Thanks.

CodePudding user response:

Here's a possible solution. Changes applied:

  • input tags no longer inside their own div
  • input tag and div containing label changed position. CSS can only look forward.

.container {
  display: flex;
  flex-direction: column-reverse;
}

input {
  width: 200px;
}

input.check div {
  color: green;
}
<div>
  <div >
    <input type="text" >
    <div>Name</div>
  </div>
  <div >
    <input type="number" >
    <div>Age</div>
  </div>
  <div >
    <input type="text">
    <div>address1</div>
  </div>
</div>

CodePudding user response:

I have to say that Gerard's idea seems pretty good and I would use it if I need it, but maybe you can also try giving classes to those elements you want to apply CSS to, so you can directly select those elements. If that's not what you want, you can also try using ntn-child, like so:

<div >
  <div>Name</div>
  <div><input type="text" >
  <div>Age</div>
  <div><input type="number" ></div>
  <div>address1</div>
  <div><input type="text"></div>
</div>

CSS

.my-class:nth-child(n) {
  color: red;
}

Take in count that n is the child number that you want to apply the code to, so depending on how many elements are inside your parent element, you can set n to one number or another.

  • Related