Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS position absolute and full width problem

Tags:

html

css

i have 2 divs and a dl:

<div id="wrap">  <div id="header">   <dl id="site_nav_global_primary"> 

and this is my style:

#wrap {     margin:0 auto;     width:100%;     min-width:760px;     max-width:1003px;     overflow:hidden; }  #header {     width:100%;     position:relative;     float:left;     padding-top:18px;     margin-bottom:29px; }  #site_nav_global_primary {         float:right;     margin-right:18px;     margin-bottom:11px;     margin-left:18px; } 

Now i want to change site_nav_global_primary to have a full screen width without changing the wrap and the header. but when i try:

#site_nav_global_primary {         position: absolute;     width:100%;     top:0px;     left:0px; } 

The navigation gets the 100% of the wrapper which is max 1003px width. i want it to stretch to the maximum without changing the wrap and header divs.

Is this possible?

like image 362
Tom Avatar asked Jul 08 '11 13:07

Tom


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.

How do you override absolute position in CSS?

position: relative; An element with position: relative; is positioned relative to its normal position. Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away from its normal position.

What happens when position is absolute in CSS?

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.

Should I avoid position absolute?

As long as you structure your HTML so that the elements follow a logical order that makes sense when rendered without CSS, there is no reason why using absolute positioning should be considered bad practice.


2 Answers

You could set both left and right property to 0. This will make the div stretch to the document width, but requires that no parent element is positioned (which is not the case, seeing as #header is position: relative;)

#site_nav_global_primary {         position: absolute;     top: 0;     left: 0;     right: 0; } 

Demo at: http://jsfiddle.net/xWnq2/, where I removed position:relative; from #header

like image 181
xec Avatar answered Oct 20 '22 10:10

xec


You need to add position:relative to #wrap element.

When you add this, all child elements will be positioned in this element, not browser window.

like image 43
Andrzej Ośmiałowski Avatar answered Oct 20 '22 10:10

Andrzej Ośmiałowski