默认为“绝对”定位和“相对”定位

时间:2012-05-25 03:19:55

标签: html css

我读到了相对和绝对定位,但是当你选择其中一个位置后没有指定“上,左,右,下”时,我仍然感到困惑。例如,在下面的代码中,我更改了容器的位置,当我将其从相对位置更改为绝对位置时,页脚会执行一些时髦的东西。我读到如果你添加“position:relative”并且没有指定任何方向,那么它将完全保持原样。但是使用firebug,我在css中切换了那条线,顶部的菜单栏会向左移动一点。发生了什么事?

HTML:
    

    <div class="container">

        <div id="header">

            <ul id="menu">
                <li><a href="#" class="active">Portfolio</a></li>
                <li><a href="#">Services</a></li>
                <li><a href="#">About</a></li>
                <li><a href="#">Testimonials</a></li>
                <li><a href="#">Request a Quote</a></li>
            </ul>       

            <div id="logo">
                <h1>Creatif</h1>
                <small>A Family of Rockstar Wordpress Themes
            </div>
        </div><!--end header-->

        <div id="block_feature">
        Featured Content
        </div>      

        <div id="block_content">
        Content

        </div>

    </div>

</div>


<div id="footer">

    <div class="container">
        Footer stuff goes here
    </div>
</div>

CSS:

@charset "UTF-8";  
/* Background-Styles */  

body {  
    margin:0px; padding:0px;  
    background-color:#131211;  
 }  
#main {  
    background:#c4c0be url(images/background_light_slice.jpg) repeat-x;  
}   
#main .container {  
    background-image:url(images/background_light.jpg);    
    background-repeat:no-repeat;  
    min-height:400px;  
}  

#header {  
    padding-top:20px;  
 }  
#logo h1, #logo small {  
    margin:0px;  
    display:block;  
    text-indent:-9999px;  
}  
#logo {  
    background-image:url(images/logo.png);  
    background-repeat:no-repeat;
    width:194px;  
    height:83px;  
}  
ul#menu {  
    margin:0px; padding:0px;  
    position:absolute;  
    right:0px;  
}  
ul#menu li {  
   display:inline;   
}




#footer {  
    background-image:url(images/background_footer.jpg);  
    background-repeat:repeat-x;  
    color:white;  
    padding:40px;  
}  
.container {  
    width:950px;  
    margin:0 auto;  
    position:relative;  
}

有位置:亲戚 enter image description here

有位置:绝对 enter image description here

2 个答案:

答案 0 :(得分:1)

您需要将#footer div设置为相对位置,因为容器必须是相对位置的绝对值。现在页脚不是相对的,所以#container默认为最接近父级的相对div。一个经验法则是在使用绝对定位时始终使容器div为相对。

#footer {position: relative; }
#container { position: absolute; }

现在,如果你将top:0添加到容器,它将是top:0到页脚。

答案 1 :(得分:0)

乍得的回答是正确的。这是一个解释:

将div设置为使用绝对位置使其相对于位置为绝对或相对的第一个父节点是绝对的。

在您的示例中,由于没有父节点设置为相对位置或绝对位置,因此该节点与主体的关系是绝对的。正如Chad所提到的,请确保将引用节点设置为position:relative。