4

I have quite a simple bit of CSS formatting - or so I thought!

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:

.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>
John Ohara
  • 2,821
  • 3
  • 28
  • 54

1 Answers1

2

Change .hidden + .visible to :not(.hidden) + .visible

CSS will continue to apply that class format, regardless of it's display: setting, because the element still exists. 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.

So let's use their class name in :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');">
TheWandererLee
  • 1,012
  • 5
  • 14