简体   繁体   English

将 css 应用于相邻元素

[英]applying css to adjacent element

Hi guys what If I have a html elements like below大家好,如果我有一个 html 元素,如下所示

 <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.我想更改之前的元素有。检查 css 属性。 something like Name -> *Name with read color.像 Name -> *Name 和读取颜色的东西。

Is it possible in CSS? CSS 有可能吗? or Do I need to mix with JS?或者我需要与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标签不再在自己的div
  • input tag and div containing label changed position.包含 label 的input标签和div更改为 position。 CSS can only look forward. CSS 只能期待了。

 .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.我不得不说 Gerard 的想法看起来不错,如果需要我会使用它,但也许您也可以尝试为您想要应用 CSS 的元素提供类,因此您可以直接 select 那些元素。 If that's not what you want, you can also try using ntn-child, like so:如果这不是您想要的,您也可以尝试使用 ntn-child,如下所示:

<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 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.考虑到 n 是您要应用代码的子编号,因此根据您的父元素中有多少元素,您可以将 n 设置为一个数字或另一个数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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