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>
Because the element, which you give absolute position take the width from his parent and didn't behave as a block element. It takes the width and height from its content. And only when the content is relatively positioned.
An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed). However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
Unfortunately, using absolute positioning means, by definition, that your element is no longer taking up space.
position: relative places an element relative to its current position without changing the layout around it, whereas position: absolute places an element relative to its parent's position and changing the layout around it.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With