css - 位置相关 DIVS

标签 css position

我总是看到这样的代码:

#container {
    background:#000000 none repeat scroll 0 0;
    display:block;
    overflow:hidden;
    position:relative;
    width:100%;
}

我认为位置相对用于使用 CSS 属性左上右下 (px) 相对于其父元素容纳 div。像下面的例子那样单独使用它有什么意义?相对位置会影响哪些其他属性?

最佳答案

子元素位置会受此影响。

在将父元素位置设置为相对位置后,当我们尝试将子元素位置设置为绝对位置时,它只会相对于父元素而不是文档绝对放置。

第一个例子

<style>
    #container 
    {
        background:red none repeat scroll 0 0;
        display:block;
        position:relative;
        top: 100px; 
        left: 100px;
        width:100%;
    }
    #child
    {
        position: absolute; 
        top: 0px;
        left: 0px;
    }

</style>
<div id="container">
    <div id="child">
        I am absolutely placed relative to the container and not to the document
    </div>
</div>

第二个例子

<style>
    #container 
    {
        background:red none repeat scroll 0 0;
        display:block;
        top: 100px; 
        left: 100px;
        width:100%;
    }
    #child
    {
        position: absolute; 
        top: 0px;
        left: 0px;
    }

</style>
<div id="container">
    <div id="child">
        I am absolutely placed relative to the container and not to the document
    </div>
</div>

试着检查上面的两个例子,你会发现不同之处。

关于css - 位置相关 DIVS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1938582/

相关文章:

html - 固定列滚动表

javascript - 如何将带有节点坐标的路径转换为带有点的 <path> 标记

java - 有效地利用位置来控制 Action

html - 调整窗口大小时将 SVG 元素固定到位

css - 即7-9不显示位置:absolute correctly

html - Internet Explorer 破坏了我的链接和 Logo

css - Bootstrap 在列表项的同一行获取链接和按钮

CSS 固定背景 z-index 问题

css - 了解 CSS 中的文本大小怪癖以进行响应式设计

html - 具有不同内容高度的粘性页脚,无需页面刷新