Wednesday, August 12, 2009

Position an element in CSS

With the position property in CSS you can place an element exactly wherever you want inside an HTML page. With using of float you can have almost every combination of positioning an element.

The positioning an element is based on the coordinates of the system. Suppose if we want to position word "ARJU" 200px from the top of the document and 300px from the left of the document with an addition attribute of red color and twice font size, then our CSS code will be,

<div style="
position:absolute;
top:200px;
left:300px;
color:red ;font-size:2em" >Arju</div>

the output is,
Arju

Note that where Arju word now positioned? In fact we have the control to put it anywhere as we want. Is not it interesting? :) Positioning an element with position parameter is really a good technique.

The position can have a value of absolute or relative. The difference between absolute and relative is, how the position value is calculated.

An element which is positioned absolute does not obtain any space in the document. This means that it does not leave an empty space after being positioned.

The position for an element which is relatively positioned is calculated from the original position in the document. That means that you move the element to the right, to the left, up or down. This way, the element still obtains a space in the document after it is positioned.

Following example should clear your idea,

<div style="position:absolute; top:500px; left:300px; color:red ;font-size:2em" >Arju</div>
<span style=" ">T1</span>
<div style="position:relative; top:500px; left:300px; color:red ;font-size:2em" >Arju2</div>
<span style=" ">T2</span>
<div style="position:absolute; top:500px; left:305px; color:red ;font-size:2em" >Arju</div>
<span style=" ">T3</span>

If you run above CSS code, you will see after "position: relative" whenever you like to display T2 it is not in the same line as in T1. But after "position:absolute" it is displayed on the same line as T2. Also we displayed both "position: relative" and "position: absolute" in the top and left value. But relative one is slightly to the right, to the left, up or down.

Arju
T1
Arju2
T2
Arju
T3

Here is more example about positioning of different boxes with top, left, right, bottom property.

#box1 {
position:absolute;
top: 550px;
left: 550px;
}

#box2 {
position:absolute;
top: 350px;
right: 350px;
}

#box3 {
position:relative;
bottom: 250px;
right: 350px;
}

#box4 {
position:relative;
bottom: 350px;
left: 650px;
}

Related Documents

1 comment:


  1. Yahoo Mail Sign Up give users access to create a new Yahoo Mail Account.
    https://tecng.com/yahoo-mail-sign-up-sign-up-for-a-yahoo-account/

    ReplyDelete