width: 50% 是什么意思,当容器是 body 时?
what does width: 50% mean when the container is body?
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。能告诉我为什么吗,这里的百分比是什么意思?
将 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>
百分比是从父元素计算的,所以如果你设置height
你也必须设置到父元素。
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>
您必须设置 height
固定才能在这种情况下工作,请在此处查看
body {
background-color: skyblue;
}
div {
width: 50%;
height: 100px;
background-color: yellow;
}
<div>
</div>
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。能告诉我为什么吗,这里的百分比是什么意思?
将 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>
百分比是从父元素计算的,所以如果你设置height
你也必须设置到父元素。
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>
您必须设置 height
固定才能在这种情况下工作,请在此处查看
body {
background-color: skyblue;
}
div {
width: 50%;
height: 100px;
background-color: yellow;
}
<div>
</div>