2

New to this, so apologies if I missed a crucial lesson in CSS...

I'm trying to do a simple exercise in CSS... a div within a div, both sized with percentages so they respond to a changing window size. Here's my code:

<head>
    <title>Percentage Test</title>
    <style>
        html, body {
            height: 100%;
            margin: 0;
        }
        #outer {
            height: 100%;
            width: 100%;
            background-color: yellow;
        }

        #inner {
            height: 90%;
            width: 90%;
            /* margin: 5%; */
            background-color: blue;
        }
    </style>
</head>


<body>
    <div id="outer"><div id="inner"></div></div>
</body>

Everything does just what I thought; the outer div takes up the whole screen and the inner div takes up 90% of the outer div. If I add to this (i.e. add another inner div, change the percentages) everything does what I would expect. If I add a surrounding margin to the inner div (in this case, 5% but commented out), I would expect the inner div to be centered (top/bottom, left/right) within the outer div. It works for the sides and the bottom but not the top. Instead, the outer div is pushed away from the body at the top (I assume 5% but I'm not sure). Any thoughts on why this happens?

  • 1
    Use box-sizing: border-box; maybe it help – Luís P. A. Jun 05 '14 at 15:30
  • Have a read: http://css-tricks.com/the-css-box-model/ – emerson.marini Jun 05 '14 at 15:31
  • Definitely a dupe - https://www.google.co.uk/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=site:stackoverflow.com+margin+pushes+parent+div – Nick R Jun 05 '14 at 15:32
  • This question is already answered here. http://stackoverflow.com/questions/3538875/css-div-width-percentage-and-padding-without-breaking-layout Check the updated version of the answer – CMPS Jun 05 '14 at 15:33

2 Answers2

2

Box-sizing will include padding and borders within the widths size.

DEMO

    #outer {
        height: 100%;
        width: 100%;
        padding:5px;
        background-color: yellow;
        box-sizing:border-box;
    }

    #inner {
        height: 100%;
        width: 100%;
        /* margin: 5%; */
        background-color: blue;
        box-sizing:border-box;
    }

TIPS

  • Top margins often fail in some browsers.

    Use margin-bottom or padding-top to create the vertical space.

  • Height 100% will not stretch to fit the outer most container without additional hacking.

    The div will only be the size of it's content.

Community
  • 1
  • 1
DreamTeK
  • 32,537
  • 27
  • 112
  • 171
1

This is the way the CSS box model works by default. The dimensions of an object is the set width/height plus any borders/margin/padding.

To have any borders/margins/padding included in the specified width, use the box-sizing:border-box; setting on that element in your CSS.

HaukurHaf
  • 13,522
  • 5
  • 44
  • 59