开发者

Why set position: relative without changing location?

I am learning css and I wonder why we set position: relative even we don't set the specific location, such as left: 20px, top: 10px. Below is a sample of css code.

#home #header {
    position: relative;
    width: 822px;
    height: 152px;
    margin: 0 19px;
    padding: 0;
 开发者_高级运维   overflow: hidden;
}

#header {
    position: relative;
    width: 822px;
    height: 152px;
    margin: 0 19px;
    padding: 0;
    overflow: hidden;
    background: url(img/bg-content-wrap-top-int.png) no-repeat center bottom;
}


Usually one of these 3 reasons:

  • To affect how elements are stacked (it changes when you position an element with or without specific z-index). See https://developer.mozilla.org/en/understanding_css_z-index
  • As Niklas Ringdahl mentioned, position:absolute elements inside will be relative to the parent if the parent is position:relative. See http://css-tricks.com/absolute-positioning-inside-relative-positioning/
  • To ensure some other property is applied as desired or fix a glitch (as a "hack"). This is done for several reasons related to IE.


In most situations it is used to set the 0,0 position for any child element that is positioned absolute inside #header.

Normally, if you do this:

<div id="header">
    <div id="fos">hehe</div>
</div>

and you use this css:

#fos {
    position: absolute;
    top: 10px;
    left: 10px;
}

your #fos element will be positioned 10,10 from the top left corner of the page. However, if you put position: relative; on #header, #fos will be positioned 10,10 from the top left corner of #header.

This would also happen if #header had anything else than position: static (which is the default value for position), but normally relative is used because it keeps the element in the document flow. So when you set it, and don't set any specific location, it will stay as it is, but 0,0 position will be changed.

I created a simple jsFiddle Demo for you.

(it is also used in some other cases as @rhyaniwyn descibed quite well, I just wanted to explain this one a bit longer, this is a very powerful technique)


It's not mandatory, but it's good to do if child elements should be use position:absolute since their relative position will be calculated against the closest parent element with position:relative

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜