我是 CSS 新手。我想知道为什么当我将div元素的定位更改为absolute时,div元素的宽度会发生变化?在 Chrome v25.0.1364.172m 和 IE9 上试了一下,结果一样。
简单的例子:
<!doctype html/>
<html>
<head>
<title>test</title>
<style>
div {
position:relative;
border-width: 1px;
border-style: solid;
border-color: black;
}
</style>
</head>
<body>
<div>test</div>
</body>
</html>
最佳答案
Because absolutely positioned elements do not behave as block level elements and do not flow after each other like normal a
<div>
does.
您需要为绝对定位的 div 设置宽度和高度,具体取决于它包含的内容。
你的绝对定位元素将相对于它所在的第一个父元素定位。所以,一个简单的例子:
一个简单的“问题”是没有将父元素设置为 position: relative;
<!-- I'm a parent element -->
<div style="width: 500px; height: 500px; position: relative; border: 1px solid blue;">
<!-- I'm a child of the above parent element -->
<div style="width: 150px; height: 150px; position: absolute; left: 10px; top: 10px; border: 1px solid red;">
I'm positioned absolutely to my parent.
</div>
</div>
关于css - 绝对位置影响宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15763027/