ovk
ovk

Reputation: 2358

Expand div automatically when floated sibling is hidden

Is it possibly to automatically expand a div to maximum width once it's floated sibling style set to display:none?

Please take a look at this example: enter image description here

Upvotes: 0

Views: 159

Answers (2)

Akash Shrivastava
Akash Shrivastava

Reputation: 1365

This is how I'd do it. See if it works for you.

document.querySelector("button").addEventListener("click", function(){
  document.querySelector(".a").classList.toggle("hidden");
});
body{
  display: block;
}
.container{
  width: 96%;
  margin-left: 2%;
}
.a, .b {
  float: right;
  height: 5em;
}
.a {
  width: 15%;
  background: #00E676;
}
.b {
  width: 85%;
  background: #1E88E5;
  font-family: Calibri;
  line-height: 2em;
}
.hidden {
  display: none;
}
.hidden ~ .b{
  width: 100%;
}
button{
  margin: 100px 100px;
}
<div class="container">
<div class="a"></div>
<div class="b"></div>
</div>
<button>Toggle</button>

Upvotes: 1

helb
helb

Reputation: 3234

It's easy with flexbox - children expand by default:

document.querySelector("button").addEventListener("click", function() {
  document.querySelector(".b").classList.toggle("hidden");
});
body {
  display: flex; /* this is the important bit */
}

div {
  border: 0.1em solid black;
  margin: 0.5em;
  padding: 0.5em;
}

.b {
  width: 15%;
  flex-shrink: 0;
}

.hidden {
  display: none;
}
<div class="a">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eu felis at metus convallis ornare. Pellentesque in porttitor elit. Sed augue augue, vulputate in laoreet quis, vehicula et arcu. Nullam feugiat elit purus, id euismod ligula sodales nec. Vestibulum mattis molestie lacus. <button>Toggle B</button>
</div>
<div class="b"></div>

Browser support is really good for some time now: https://caniuse.com/#feat=flexbox

Another option would be display: table:

document.querySelector("button").addEventListener("click", function() {
  document.querySelector(".b").classList.toggle("hidden");
});
body {
  display: table;
  border-spacing: 1em;
  border-collapse: separate;
}

.a, .b {
  border: 0.1em solid black;
  padding: 0.5em;
  display: table-cell;
  height: 5em;
}

.a {
  width: 85%;
}

.b {
  width: 15%;
}

.hidden {
  display: none;
}
<div class="a">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eu felis at metus convallis ornare. Pellentesque in porttitor elit. Sed augue augue, vulputate in laoreet quis, vehicula et arcu. Nullam feugiat elit purus, id euismod ligula sodales nec.
  Vestibulum mattis molestie lacus. <button>Toggle B</button>
</div>
<div class="b"></div>

But… it feels kinda hacky to me. Just use flexbox if you don't need support for ancient browsers.

Upvotes: 2

Related Questions