AntonioJunior
AntonioJunior

Reputation: 959

How to set CSS width so that the element will have the exact window width?

I am using the following CSS code to stretch an element (<header> in this example) so that it fits the browser window width:

header {
    font-size: small;
    color: white;
    overflow: auto;
    background-color: rgba(51, 51, 51, .8);
    padding: 3px 3px;
    width: 100%;
}

but the problem is that this element, or any to which I apply width: 100%; overflow: auto; overflows the window limits:

| <--- window width ---> |
|  <--- element width ---> |

How can I set the CSS properties so that the element width fits exactly the window width?

| <--- window width ---> |
| <--- element width --> |

Upvotes: 1

Views: 2227

Answers (4)

Alex Simitsis
Alex Simitsis

Reputation: 31

You should use box-sizing: border-box; That means that the width of an element remains the same either you add border or padding, or even both of them.

Upvotes: 3

chickpeas
chickpeas

Reputation: 443

If you remove width:100% it should work with the one div solution

header {
font-size: small;
color: white;
overflow: auto;
background-color: rgba(51, 51, 51, .8);
padding: 3px 3px;

}

usually there's no need to set the width:100% on block elements

Upvotes: 1

Shikiryu
Shikiryu

Reputation: 10219

<header>
    <div>
    </div>
</header>

And CSS :

header{
    font-size: small;
    color: white;
    overflow: auto;
    background-color: rgba(51, 51, 51, .8);
    width: 100%;
}
header div{
    margin:3px 3px;
    display:block;
}

Example here : http://jsfiddle.net/Chouchen/mvs79/

Upvotes: 1

Dave
Dave

Reputation: 29141

Remove your padding. Adding padding adds additional width. So, your statement is like saying "make it 100% wide, but then add 6px.

If you want it to be fullscreen WITH padding, make it fullscreen, then add a div within it that has the padding.

Upvotes: 3

Related Questions