Changing Element Location



By default, all HTML elements flow statically from left to right in the same order that they are declared in the HTML page. However, CSS provides a mechanism to specify some advanced options in element position.

Absolute Positioning

You can position elements by using absolute positioning or relative positioning. With absolute positioning, the element is placed in the exact location specified, relative to its container’s borders.

You can apply four properties individually or in combination to control the position of an element: Top, Left, Right, and Bottom.

Each property takes a distance parameter that specifies the relative distance of the object from a reference point based on the positioning attribute specified.

The following code gives an example of absolute positioning between two images:

<head>
<style type="text/css">
    html, body {
        height: 100%;
        width: 100%;
    }
    img {
        height: 150px;
        width: 225px;
        border: 1px solid blue;
    }
    img#image2 {
        left: 150px;
        top: 55px;
        position: absolute;
    }
</style>
</head>
<body>
    <img id="image1" src="image1.jpg" />
    <img id="image2" src="image2.jpg" />
</body>

Relative Positioning

You can also apply relative positioning. With relative positioning, the element is positioned relative to its immediate left sibling’s coordinates.

The following code gives an example of relative positioning between two images:

<head>
<style type="text/css">
    html, body {
        height: 100%;
        width: 100%;
    }
    img {
        height: 150px;
        width: 225px;
        border: 1px solid blue;
    }
    img#image2 {
        left: 150px;
        top: 55px;
        position: relative;
    }
</style>
</head>
<body>
    <img id="image1" src="image1.jpg" />
    <img id="image2" src="image2.jpg" />
</body>

Static Positioning

This is the default for every single page element. Different elements don't have different default values for positioning, they all start out as static. Static doesn't mean much, it just means that the element will flow into the page as it normally would.

The only reason you would ever set an element to position: static is to forcefully-remove some positioning that got applied to an element outside of your control.

Fixed Positioning

This type of positioning is fairly rare but certainly has its uses. A fixed position element is positioned relative to the viewport, or the browser window itself.

The viewport doesn't change when the window is scrolled, so a fixed positioned element will stay right where it is when the page is scrolled.


PROMOTIONS