为什么div在其他div中失去输出%的能力?

时间:2016-10-28 05:01:48

标签: html css pixel percentage elements

<divs>位于其他<divs>内时,为什么<div id="2">会失去以%(百分比)输出宽度和高度的能力?

我在<div id="3">内有<div id="1"><div id="1">

<div id="2">的宽度和高度设置为%(百分比)。

当我将它们设置为%时,<div id="3">@EJB高度怎么办不起作用? (他们使用px(像素)。)

2 个答案:

答案 0 :(得分:1)

%是相对测量单位,因此您需要将任何父级设置为绝对单位,例如px 例如,如果您的div1为空,则div1为100% width and 0% height,在这种情况下,您的div2 and div3将无效。

将你的html,正文宽度和高度设置为100%,你的所有div应该正常工作 试试这段代码;

body, html{
  height: 100%;
  background: #eee;
}

.div1{
  width: 100%;
  height: 100%;
  background: #ccc;
}

.div2{
  width: 50%;
  height: 50%;
  background: #888;
  margin-left: 50%;
}

.div3{
  width: 50%;
  height: 50%;
  background: #fff;
}

SEE WORKING EXAMPLE

答案 1 :(得分:0)

在div1中使用position:relative他们只有内部div将占用%height而div相对于父

.parent {
  position: relative;
  width: 300px;
  height: 100px;
  background: #eee;
}
#div1 {
  position: relative;
  width: 80%;
  background: #f00;
  height: 80%;
  display: inline-block;
}
#div2 {
  width: 30%;
  background: #0f0;
  height: 30%;
  display: inline-block;
}
#div3 {
  width: 30%;
  background: #00f;
  height: 30%;
  display: inline-block;
}
<div class='parent'>
  <div id="div1">
    <div id="div2">
    </div>
    <div id="div3">
    </div>
  </div>
</div>