Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

absolute position affects width?

Tags:

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> 
like image 798
lee23 Avatar asked Apr 02 '13 11:04

lee23


People also ask

Why does position absolute affect width?

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.

What does absolute positioning effect?

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.

Does position absolute take up space?

Unfortunately, using absolute positioning means, by definition, that your element is no longer taking up space.

What is the difference between absolute and relative position?

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.


1 Answers

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 image 155
SMacFadyen Avatar answered Dec 05 '22 17:12

SMacFadyen