什么是宽度:50%意味着什么时候容器是身体?

时间:2016-08-03 12:23:02

标签: html css width css-position percentage

body {
  background-color: skyblue;
}
div {
  width: 50%;
  height: 50%;
  background-color: yellow;
}
<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <div>
  </div>
</body>

</html>

我已经知道宽度百分比表示与容器相比的比率。但是,当我为div的宽度和高度分配50%时,我看不到div。你能告诉我为什么,以及这里的百分比意味着什么?

4 个答案:

答案 0 :(得分:1)

position: absolute添加到div,就是这样!

请了解position如何处理DOM元素。

body {
  background-color: skyblue;
}
div {
  width: 50%;
  height: 50%;
  background-color: yellow;
  position: absolute;
}
<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <div>
  </div>
</body>

</html>

答案 1 :(得分:1)

百分比是根据父元素计算的,因此如果设置height,您还必须设置为父元素。

答案 2 :(得分:0)

body {
  background-color: skyblue;
  height : 100px;
}
div {
  width: 50%;
  height: 50%;
  background-color: yellow;
  position:absolute;
}
<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <div>
  </div>
</body>

</html>

答案 3 :(得分:0)

在这种情况下,您必须将height设置为有效,请点击此处

body {
  background-color: skyblue;
}
div {
  width: 50%;
  height: 100px;
  background-color: yellow;
}
<div>
 </div>

相关问题