user429620
user429620

Reputation:

width: 100% with position: absolute

If you do:

<div style="width: auto; background: red; color: white">test</div> 

You get a div that is stretched to fill the entire screen width (100%). That is what I need to happen.

However, I also need the starting position to be set. So, I need position: absolute.

When I add position:absolute, the width of the div is only as wide as the content within (similar to floats). Is there any way around this?

I cannot simply specify width: 100% since this does not take in to account border sizes, etc.

Upvotes: 22

Views: 36136

Answers (3)

thirtydot
thirtydot

Reputation: 228182

When I add position:absolute, the width of the div is only as wide as the content within.. (Similar to floats). Is there any way around this?

I cannot simply specify width:100% since this does not take in to account border sizes, etc..

You could use position:absolute; left:0; right:0; top:0.

Like this: http://jsfiddle.net/thirtydot/yQWGV/

Upvotes: 27

sandeep
sandeep

Reputation: 92793

simply write like this:

div.absolute {
    border: 5px solid #000;
    background-color: #F00;
    position: absolute;
    top: 100px;
    padding: 50px;
    left:0;
    right:0;
}

http://jsfiddle.net/dJtm2/1/

in this padding & border not increase the width of the element.

Upvotes: 2

Andreas Eriksson
Andreas Eriksson

Reputation: 9027

You can use width:100% and the css attribute box-sizing, to get the box model working like IE 5.5, i.e. padding and border counted into the width.

div.absolute {
    width: 100%;
    border: 5px solid #000;
    background-color: #F00;
    position: absolute; top: 100px;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    padding: 50px;
}

Here's a fiddle: http://jsfiddle.net/dJtm2/

Be wary though, as it's a relatively new CSS3 attribute and will only work in newer browsers, and as you can see from my example requires the dreadful counter-productive measure that is vendor prefixes.

Upvotes: 3

Related Questions