简体   繁体   English

相邻的同级匹配具有显示的元素:无

[英]Adjacent sibling matches elements with display: none

I have quite a simple bit of CSS formatting - or so I thought! 我的CSS格式相当简单-还是我想!

I have two adjacent elements, the first of which can be hidden. 我有两个相邻的元素,其中第一个可以隐藏。 I've used display: none to hide it. 我已经使用显示:没有隐藏它。

The second element is always present. 第二个元素始终存在。

I need to maintain a space between the two, so I thought the following bit of CSS would be sufficient: 我需要在两者之间保持一个空间,所以我认为下面的CSS足够了:

.hidden + .visible {
    margin-left: 200px;
}   

However, it seems that although the first element has display: none applied, the selector is still matches the second element as adjacent (not first), so applies the margin. 但是,似乎第一个元素没有显示:没有应用显示,但选择器仍然与第二个元素匹配(而不是第一个),因此应用了边距。

Aside from finding it quite 'odd', I need to find a way of keeping a space between the two, but only when both are visible. 除了发现它很“奇怪”之外,我还需要找到一种在两者之间保持空间的方法,但前提是两者都可见。

Any ideas? 有任何想法吗?

There's a snippet attached with an example. 有一个附带示例的代码段。

 .container { margin: 50px; } .wrapper { background-color: aqua; display: flex; justify-content: flex-start; } .item { background-color: red; flex: 0 0 auto; height: 40px; width: 40px; } .hidden { display: none; } .visible { background-color: lime; } .hidden + .visible { margin-left: 200px; } 
 <div class="container"> <div class="wrapper"> <div class="item hidden">hidden</div> <div class="item visible">visible</div> </div> </div> 

Change .hidden + .visible to :not(.hidden) + .visible .hidden + .visible更改为:not(.hidden) + .visible

CSS will continue to apply that class format, regardless of it's display: setting, because the element still exists. CSS会继续采用该类格式,而不管其display:设置如何,因为该元素仍然存在。 And according to this answer I believe there isn't any way for a plain CSS selector to tell something's display is :none unless it is inline. 根据这个答案,我相信普通的CSS选择器没有任何办法可以告诉显示的内容是:none,除非它是内联的。

So let's use their class name in :not(.hidden) . 因此,让我们:not(.hidden)使用它们的类名 See below. 见下文。

 .container { margin: 50px; } .wrapper { background-color: aqua; display: flex; justify-content: flex-start; } .item { background-color: red; flex: 0 0 auto; height: 40px; width: 40px; } .hidden { display: none; } .visible { background-color: lime; } :not(.hidden) + .visible { margin-left: 200px; } 
 <div class="container"> <div class="wrapper"> <div class="item hidden">hidden</div> <div class="item visible">visible</div> </div> </div> <input type="button" value="Show/Hide" onclick="var cn=document.getElementsByClassName('item')[0].className; document.getElementsByClassName('item')[0].className=(cn=='item visible'?'item hidden':'item visible');"> 

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

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