Rui Xia
Rui Xia

Reputation: 175

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;
}

Upvotes: 0

Views: 1175

Answers (3)

kapa
kapa

Reputation: 78741

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)

Upvotes: 2

morewry
morewry

Reputation: 4448

Usually one of these 3 reasons:

Upvotes: 8

Niklas Wulff
Niklas Wulff

Reputation: 3524

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

Upvotes: 1

Related Questions