隐藏浮动的兄弟时自动展开div

时间:2017-11-10 00:41:39

标签: html css

一旦将div的浮动样式设置为display:none,是否可以自动将div扩展到最大宽度?

请看一下这个例子: enter image description here

2 个答案:

答案 0 :(得分:1)

使用flexbox很容易 - 默认情况下,子项会展开:

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>

浏览器支持现在已经很好了:https://caniuse.com/#feat=flexbox

另一种选择是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>

但是......对我来说这感觉有点不好意思。如果您不需要支持古代浏览器,请使用flexbox。

答案 1 :(得分:1)

我就是这样做的。看看它是否适合你。

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>