Page 1 of 1

I'm having some troubles with width in CSS

Posted: Tue Sep 01, 2009 11:00 pm
by insight
I have been setting a lot of my blocks to a width of 100% so it can stretch to fit the whole screen. But I have a problem with setting with to 100% inside a block that's already set to 100%. As shown in this picture:
Image

Code here for the blue header (General settings):

Code: Select all

#block-header{
    -moz-border-radius: 10px;
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    -webkit-border-radius: 10px;
    background-color:#D7FFFF;
    border:1px solid #7FF;
    color:#06F;
    height:auto;
    margin:5px;
    padding:3px;
    width:100%;
}
Should I just set the width to auto?

EDIT: Just set width to auto and everything seems to be fine. Why doesn't setting it to 100% work?

Re: I'm having some troubles with width in CSS

Posted: Tue Sep 01, 2009 11:21 pm
by matthijs
You don't have to set any width on block level elements like a div (or h1,h2,etc): they will have a width of auto already. Which means the browser will calculate the width based on a few factors. If you don't have margin, padding and border set for the div, it will always take up 100% of the width. If you do have a margin/padding and/or border set, the auto width will be what remains.

Search for "box model css" and read up on how the box model works. That will help prevent many future problems.

Hope this helps

Re: I'm having some troubles with width in CSS

Posted: Tue Sep 01, 2009 11:27 pm
by insight
matthijs wrote:You don't have to set any width on block level elements like a div (or h1,h2,etc): they will have a width of auto already. Which means the browser will calculate the width based on a few factors. If you don't have margin, padding and border set for the div, it will always take up 100% of the width. If you do have a margin/padding and/or border set, the auto width will be what remains.

Search for "box model css" and read up on how the box model works. That will help prevent many future problems.

Hope this helps
Cheers, and yes I do have margins/paddings and borders but didn't know they wouldn't work if you used 100% on divs on them. But it does make sense and I understand now. Won't be making the same mistake, am still new to this stuff so got a lot to learn :D