NtsDK NtsDK - 20 days ago 6
HTML Question

How to make conditional margin for hideable flex panels?

I have initial html:



body {
background-color: grey;
}
.container{
display: flex;
width: 200px;
height: 100px;
background-color: red;
}
.panel{
height: 100%;
flex-grow: 1;
flex-basis: 50%;
color: white;
}
.left{
background-color: green;
}
.left{
margin-right: 8px;
}
.right{
background-color: blue;
}
.hidden{
display: none;
}

<div class="container">
<div class="left panel ">left</div>
<div class="right panel ">right</div>
</div>





It makes two panels of equal width with 8px margin between them. Fiddle

Looks:

how it looks

Then I need to hide right or left or both panels with hidden class.

I have new html (fiddle):

<div class="container">
<div class="left panel ">left</div>
<div class="right panel hidden">right</div>
</div>


Result:

enter image description here

How to remove margin if there is one panel and show margin if there are two panels?
I can't just move margin from left to right panel because I need possibility to hide both panels independently.

UPD 1. I can't remove panels from dom. It should use hidden class.

Answer

You can do it without removing the panels from DOM:

  1. Instead of margin-right on left panel, use margin-left on the right panel.

  2. Use the below styles to get rid of the margin when either of left or right has the class hidden:

    .container > .left.hidden + .right{
      margin-left:0;
    }
    

See demo below:

body {
  background-color: grey;
}
.container {
  display: flex;
  width: 200px;
  height: 100px;
  background-color: red;
}
.panel {
  height: 100%;
  flex-grow: 1;
  flex-basis: 50%;
  color: white;
}
.left {
  background-color: green;
}
.right {
  background-color: blue;
  margin-left: 8px;
}
.hidden {
  display: none;
}
.container > .left.hidden + .right{
  margin-left:0;
}
<div class="container">
  <div class="left panel">left</div>
  <div class="right panel">right</div>
</div>
<br/>
<div class="container">
  <div class="left panel">left</div>
  <div class="right panel hidden">right</div>
</div>
<br/>
<div class="container">
  <div class="left panel hidden">left</div>
  <div class="right panel">right</div>
</div>
<br/>
<div class="container">
  <div class="left panel hidden">left</div>
  <div class="right panel hidden">right</div>
</div>