100% width with margin/padding/border?

Discussion in 'CSS' started by wd_2k6, Apr 20, 2008.

  1. #1
    Hi i have a div nested inside another one, the question is how can i make this nested div have 100% width, with 10px margin?

    The problem I am getting is that whenever I add margin/padding/border it adds to the width already specific so in this case its 100% + the margin also, whereas i need it to be 100% altogether? Is this even possible?

    For more information here's a quick example:

    CSS:
    <style type="text/css" media="screen">
    #div1 { width: 50%; background-color: red;}
    .nested {width: 100%; margin:10px; background-color: pink;}
    </style>

    HTML:
    <body>
    <div id="div1">
    <div class="nested">Hey why am I out of the box?! And where is the margin-top?!</div>
    Hey You're not Allowed in here!
    </div>
    </body>
     
    wd_2k6, Apr 20, 2008 IP
  2. dzdrazil

    dzdrazil Peon

    Messages:
    64
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    width specifies the size of a content block, not counting margin, padding or border. setting 100% plus 10px creates a 10px overflow, which you need to hide (add overflow:hidden to div1 css). of course, there won't be a margin on the right side then, as the right side margin isn't preserved. The good news is, margin-top comes back!
    Or, you could just set width to 96% and margin to 2%... or some other combination that adds margin-left, right and content up to 100% total, depending on your preference.


    ironically, IE7 displays what you want in quirks mode, but loses it when it has a doctype... i believe this was microsoft's attempt at fixing IE6's issue with any content box that didn't have a fixed width (overflow wouldn't hide)

    hope this helps!
     
    dzdrazil, Apr 20, 2008 IP
    wd_2k6 likes this.
  3. wd_2k6

    wd_2k6 Peon

    Messages:
    1,740
    Likes Received:
    54
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks for the advice, I never thought about adding % to margin, will give that a try!!
     
    wd_2k6, Apr 20, 2008 IP
  4. dzdrazil

    dzdrazil Peon

    Messages:
    64
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #4
    also, don't forget that you should be able to do something like margin: 10px 2%; so that top and bottom are set at 10px and the sides look ok at any width ;)
     
    dzdrazil, Apr 20, 2008 IP