简体   繁体   中英

applying css to adjacent element

Hi guys what If I have a html elements like below

 <div> <div>Name</div> <div><input type="text" class="check"> <div>Age</div> <div><input type="number" class="check"></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.

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 class="container"> <input type="text" class="check"> <div>Name</div> </div> <div class="container"> <input type="number" class="check"> <div>Age</div> </div> <div class="container"> <input type="text"> <div>address1</div> </div> </div>

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 class="my-class">
  <div>Name</div>
  <div><input type="text" class="check">
  <div>Age</div>
  <div><input type="number" class="check"></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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM