Reputation: 65
I have two child divs inside a parent div. The first child div is 32% of the width, and the second child div is 68% of the width. If the first child div is set to display: none;
, how do I make it so that the second child div goes from 68% of the width to 100% of the width? Thanks
.parent {
width: 400px;
height: 200px;
position: relative;
float: left;
display: inline-block;
}
.child1 {
width: 32%;
height: 100%;
float: left;
background-color: green;
}
.child2 {
width: 68%;
height: 100%;
float: left;
background-color: red;
}
<div class='parent'>
<div class='child1'></div>
<div class='child2'></div>
</div>
Upvotes: 0
Views: 2132
Reputation: 311
here's how you can achieve that using your approach.
<div class="parent">
<div class="child1"></div>
<div class="child2"></div>
</div>
.parent {
width: 400px;
height: 200px;
font-size: 20px;
font-weight: bold;
color: white;
}
.child1 {
width: 32%;
height: 100%;
float: left;
background-color: green;
}
.child2 {
width: 100%;
height: 100%;
background-color: blue;
}
Upvotes: 0
Reputation: 2132
Here instead of using float property you can use Flexbox. for more understanding follow this link.
so in flexbox you can achieve it by following the below code :-
.parent {
width: 400px;
height: 200px;
display: flex;
}
.child1 {
height: 100%;
background-color: green;
flex:1;
}
.child2 {
// display:none;
height: 100%;
flex:2;
background-color: red;
}
<div class='parent'>
<div class='child1'></div>
<div class='child2'></div>
</div>
Upvotes: 1
Reputation: 27245
If you use flex instead of float, setting display: none
on one will adapt the other for you:
document.querySelector('button').addEventListener('click', () => {
document.querySelector('.child1').classList.toggle('hidden');
})
.parent {
width: 400px;
height: 200px;
position: relative;
display: flex;
}
.child1 {
flex: 0 0 32%;
background-color: green;
}
.child2 {
flex: 1 1 auto;
background-color: red;
}
.hidden {
display: none;
}
button {
margin-bottom: 1em;
}
<button>Toggle child1 visibility</button>
<div class='parent'>
<div class='child1'></div>
<div class='child2'></div>
</div>
Upvotes: 2
Reputation: 7415
I would leverage the magic of flex!
flex: 0 0 32%;
On child1 sets the width to 32%.
flex: 1;
to the child2 means: Fill all the available space. So if the child1 disappears, child 2 will fill all the remaining space.
.parent {
width: 400px;
height: 200px;
display: flex;
}
.child1 {
flex: 0 0 32%;
background-color: green;
}
.child2 {
flex: 1;
background-color: red;
}
<div class='parent'>
<div class='child1'></div>
<div class='child2'></div>
</div>
Upvotes: 3