CSS using percentage and margin, padding or border

12,000

Solution 1

That's totally normal. It's not what you might expect at first, but CSS works that way.

Even without percentages:

#width {
    width: 100px;
    padding: 0 20px;
}

This #width div will occupy 140px. Works the same for percentages.

So you might need inner divs to achieve what you want.

<div class="left">
   <div class="inner">

   </div>
</div>
<div class="right">
   <div class="inner">
   </div>
</div>


.inner { padding: 10px; }
.right .inner { border-left: 1px solid #ccc; }

Solution 2

What you can do to fix this issue is to use box-sizing. See http://jsfiddle.net/Marwelln/YYkxK/

box-sizing:border-box

Solution 3

Padding or Border always adds to an elements size, inside out.

Margin never adds to size but adds space outside the element.

Percentages or set values don't matter. The above is always true.

Reviewing the box model may help ---> HERE

Share:
12,000
Alex004
Author by

Alex004

I'm working with JAVA, JSP, Eclipse, tomcat for several web projects.

Updated on June 04, 2022

Comments

  • Alex004
    Alex004 about 2 years

    I have a problem which I do not understand. If I use percentage in width, I would expect that elements calculate borders, margins or paddings within their size (in percentage). But in fact those values are added to their size which I asume is wrong. Is my expectation wrong? The bellow example shows the issue. The both "divs" "left" and "right" I expect to be in a single line. If I remove "border" it works as expected.

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    .center {
      border: 1px solid black;
      width: 100%;
      overflow: auto;
    }
    
    .left {
      border: 1px solid black;
      width: 20%;
      float: left;
    }
    
    .right {
      border: 1px solid black;
      width: 80%;
      float: left;
    }
    </style>
    </head>
    <body>
    <div class="center">
      <div class="left">left</div>
      <div class="right">right</div>
    </div>
    </body>
    </html>