-3

Please consider this image:

enter image description here

I can create such these divs but the problem is when one of these divs being invisible other can fill entire line.

How can i do this?

<div id="container">
   <div id="left"> left</div>
   <div id="right"> right</div>
</div>

CSS:

#left {
   background: #aaa;
   display: inline-block;
   width: 49%;
}

#right {
   background: cyan;
   display: inline-block;
   width: 49%;
}

#container {
  background: red;
  width: 100%
}

Demo: https://jsfiddle.net/ynuL2za5/

Arian
  • 12,793
  • 66
  • 176
  • 300

2 Answers2

1

You can achieve this with display: flex, making each div flex-grow:1 to fill the parent container. I have added a button to demonstrate that when the left div is hidden (by adding a hidden class) - that allows the right side to expand to fill the container.

var leftDiv = document.querySelector('#left-div');
function toggleDiv(){
 leftDiv.classList.toggle('hidden');
}
.wrapper { 
display: flex;
}

.wrapper div {
 flex-grow: 1;
 
 height: 300px;
}

#left-div { background: lime;}
#right-div { background: aqua;}

.hidden {display: none}
<button type="button" onclick="toggleDiv()"> Toggle left Div </button>

<hr/>


<div class="wrapper">
 <div id="left-div"> Lorem ipsum left</div>
 <div id="right-div"> Lorem ipsum right</div>
</div>

Conversely if the right side is hidden - the left will fill the container .

var rightDiv = document.querySelector('#right-div');
function toggleDiv(){
 rightDiv.classList.toggle('hidden');
}
.wrapper { 
display: flex;
}

.wrapper div {
 flex-grow: 1;
 
 height: 300px;
}

#left-div { background: lime;}
#right-div { background: aqua;}

.hidden {display: none}
<button type="button" onclick="toggleDiv()"> Toggle right Div </button>

<hr/>


<div class="wrapper">
 <div id="left-div"> Lorem ipsum left</div>
 <div id="right-div"> Lorem ipsum right</div>
</div>
gavgrif
  • 15,194
  • 2
  • 25
  • 27
1

I would recommend you use display: flex

CSS:

#container {
  display: flex;
  background: red;
  width: 100%;
  height: 300px; // <== as per your requirement
}

#left, #right {
  flex: 1   // <= to make them take equal space in container
}

#left {
   background: #aaa;
}

#right {
   background: cyan;
}

Now if any of div is hidden display:none the other one will automatically span to take up full available width to fill container space.

Also for better performance, I would recommend you to use classes instead of id.

Sushmit Sagar
  • 1,412
  • 2
  • 13
  • 27