不要填补空间更多的div

时间:2016-04-30 18:21:09

标签: html css

我有这个代码

<div id="menu_right_levels">
    <div class="level"> Livello 1 </div>
    <div class="level"> Livello 2 </div>
    <div class="level"> Livello 3 </div>
    <div class="level"> Livello 4 </div>
    <div class="level"> Livello 5 </div>
    <div class="level"> Livello 6 </div>
    <div class="level"> Livello 7 </div>
    <div class="level"> Livello 8 </div>
    <div class="level"> Livello 9 </div>
    <div class="level"> Livello 10 </div>
</div>

这个风格

 .level {
  width: 100%;
  height: 10%;
  border: 1px solid black;
 }

我需要一个响应div来自动填充他并且具有相同的高度,我不知道是什么,但是我的10个div,高度:10%看起来如此:

enter image description here

2 个答案:

答案 0 :(得分:3)

这是因为边界:每个div实际上 10%+ 2px 高。你需要的是CSS box-sizing: border-box;属性。使用height时,CSS var boxSizing = "border-box"; var els = document.getElementsByClassName("level"); function toggleBoxSizing(e) { if (boxSizing == "border-box") { boxSizing = "content-box"; e.target.innerHTML = "Enable box-sizing"; } else { boxSizing = "border-box"; e.target.innerHTML = "Disable box-sizing"; } for (var i = 0; i < els.length; i++) { els[i].style.boxSizing = boxSizing; } }属性也会应用于填充和边框

JSFiddle:enter image description here

&#13;
&#13;
body {
  margin: 0;
  padding: 0;
}
#orange {
  background-color: #FF4500;
  height: 940px;
}
#menu_right_levels {
  float: right;
  height: 940px;
  width: 380px;
  background-color: #1E90FF;
}
.level {
  width: 100%;
  height: 10%;
  border: 1px solid black;
  text-align: center;
  box-sizing: border-box;
 }
&#13;
<div id="menu_right_levels">
    <div class="level"> Livello 1 </div>
    <div class="level"> Livello 2 </div>
    <div class="level"> Livello 3 </div>
    <div class="level"> Livello 4 </div>
    <div class="level"> Livello 5 </div>
    <div class="level"> Livello 6 </div>
    <div class="level"> Livello 7 </div>
    <div class="level"> Livello 8 </div>
    <div class="level"> Livello 9 </div>
    <div class="level"> Livello 10 </div>
</div>
<div id="orange">
  <button onclick="toggleBoxSizing(event)">Disable box-sizing</button>
</div>
&#13;
SearchResponse
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这是因为你的边界。每个div基本上都是10%+ 2px高。 2px加起来(准确地加起来为20px)。

一个简单的解决方案是在红色div中添加填充以弥补额外的20个像素:

#container {
  height: 600px
}
#left {
  background: red;
  float: left;
  height: 100%;
  width: 100px;
  padding-bottom: 20px; /* BOTTOM PADDING ADDED */
}
#menu_right_levels {
  float: left;
  width: 300px;
  height: 100%
}
.level {
  width: 100%;
  height: 10%;
  border: 1px solid black;
}
<div id="container">
  <div id="left"></div>

  <div id="menu_right_levels">
    <div class="level">Livello 1</div>
    <div class="level">Livello 2</div>
    <div class="level">Livello 3</div>
    <div class="level">Livello 4</div>
    <div class="level">Livello 5</div>
    <div class="level">Livello 6</div>
    <div class="level">Livello 7</div>
    <div class="level">Livello 8</div>
    <div class="level">Livello 9</div>
    <div class="level">Livello 10</div>
  </div>
</div>