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.17
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>
Like SMacFadyen said, the most likely cause is missing position relative in the container
.
However, if the container
is in position relative and has a small width and the inner
content in absolute, when you position the inner content using left or right its content might break into multiple lines. In this scenario you will want to change the white-space property to nowrap
or some other option that better suits your needs.
Because the element, which you give absolute position take the width from his parent and didn't behave as a block element.