Jim Jim - 2 months ago 12
CSS Question

CSS calc percentage width and division

I have menu which is a list with three list-items:

<ul class="menu_container">
<li class="item">Item1</li>
<li class="item">Item2</li>
<li class="item">Item3</li>
</ul>


The width of the ul element changes as you resize the browser and I'm trying to use calc to workout the widths of the items so that they are equal. The first and third list-items have a 2px wide left and right border.

In the Chrome dev tools the width of menu_container is 636px. If I inspect the first list-item and do
width: 100%
it shows 640px. But if I do
calc((100% - 12px) / 3)
it shows 212px for the width. Why is this not (640 - 12) / 3 = 209.333?

Answer

Box-sizing:border-box

With box-sizing:border-box the dimension is calculated as, width = border + padding + width of the content, and height = border + padding + height of the content.

Example

width = 100px + 2px border on both side = 4px + padding 5px on both side = 10px

The total will be 100px + 4px + 10px = 114px

With box-sizing:borderbox property

The total will be 100px because the border and padding is given from inside