absolute position affects width?

lee23 picture lee23 · Apr 2, 2013 · Viewed 23.7k times · Source

I am new to css. I am wondering why when I change the positioning of the div element to absolute, the width of the div element changes? Tried it out in Chrome v25.0.1364.172m and IE9, both have the same outcome.

Simple example:

<!doctype html/>
<html>
<head>
    <title>test</title>
    <style>
        div {
            position:relative;
            border-width: 1px;
            border-style: solid;
            border-color: black;
        }
    </style>
</head>
<body>
    <div>test</div>
</body>
</html>

Answer

SMacFadyen picture SMacFadyen · Apr 2, 2013

Because absolutely positioned elements do not behave as block level elements and do not flow after each other like normal a<div>does.

You will need to set a width and a height for a div that is absolutely positioned, depending what it contains.

Your absolutely positioned element will position relative to the first parent element it is in. So, a simple example:

A simple 'gotcha' is not setting the parent element to have position: relative;

<!-- I'm a parent element -->
<div style="width: 500px; height: 500px; position: relative; border: 1px solid blue;">

    <!-- I'm a child of the above parent element -->
    <div style="width: 150px; height: 150px; position: absolute; left: 10px; top: 10px; border: 1px solid red;">
         I'm positioned absolutely to my parent. 
    </div>

</div>