CSS 绝对位置影响宽度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15763027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 22:17:38  来源:igfitidea点击:

absolute position affects width?

csspositionwidthabsolute

提问by lee23

I am new to css. I am wondering why when I change the positioning of the div element to absolute, the width of the div element changes? Tried it out in Chrome v25.0.1364.172m and IE9, both have the same outcome.

我是 css 新手。我想知道为什么当我将div元素的定位更改为absolute时,div元素的宽度会发生变化?在 Chrome v25.0.1364.172m 和 IE9 中尝试过,结果相同。

Simple example:

简单的例子:

<!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>

回答by SMacFadyen

Because absolutely positioned elements do not behave as block level elements and do not flow after each other like normal a<div>does.

因为绝对定位的元素不会像块级元素那样表现,也不会像正常的 a 那样一个接一个地流动<div>

You will need to set a width and a height for a div that is absolutely positioned, depending what it contains.

您需要为绝对定位的 div 设置宽度和高度,具体取决于它包含的内容。

Your absolutely positioned element will position relative to the first parent element it is in. So, a simple example:

你的绝对定位元素将相对于它所在的第一个父元素定位。所以,一个简单的例子:

A simple 'gotcha' is not setting the parent element to have position: relative;

一个简单的“陷阱”不是将父元素设置为 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>

回答by Aladdin Ahmed Muhammad

Because the element, which you give absolute position take the width from his parent and didn't behave as a block element.

因为你赋予绝对位置的元素从他的父元素中获取宽度,而不是块元素。

回答by Tiagojdferreira

Like SMacFadyen said, the most likely cause is missing position relative in the container. However, if the containeris in position relative and has a small width and the innercontent in absolute, when you position the inner content using left or right its content might break into multiple lines. In this scenario you will want to change the white-spacepropertyto nowrapor some other option that better suits your needs.

就像 SMacFadyen 所说的那样,最可能的原因是在container. 但是,如果container位置相对且宽度较小且inner内容绝对,则当您使用 left 或 right 定位内部内容时,其内容可能会分成多行。在这种情况下,您需要将white-space属性更改为nowrap或其他更适合您需要的选项。