Consistent HTML Element Sizing

| | 1 min read

The problem: HTML elements have inconsistent sizes across different browsers.

The solution: Set box-sizing for all elements to border-box.

A long-time bane for web developers, Internet Explorer did one thing right: It sized boxes properly.

Other browsers only look at the content when calculating the width of an HTML element, with everything else treated as surplus. A width: 200px div, with 20px padding and a 2px border, renders as 242 pixels wide.

Internet Explorer considers padding and border as a part of the width. Here, the div from above would be 200 pixels wide.

HTML:

<div class="container">

    <div class="content">

        If you're looking at this box a browser that's <em>not</em> an older version of Internet Explorer, 

        it's actually 242 pixels wide, even though its <code>width</code> was set to <code>200px</code> 

        (200 pixel content + 20 pixel padding on both sides + 1 pixel left and right border width).

    </div>

</div>

 

 

SCSS:

.container {

    & {

        width: 200px;

        padding: 20px;

        background: #eee;

        border: 1px solid black;

    }

    > .content {

        background: #ddd;

    }

}

In any case, the following CSS keeps element sizes (and therefore layouts) consistent across all browsers:

Updated SCSS:

html {

    box-sizing: border-box;

}

*, *:before, *:after {

    box-sizing: inherit;

}



.container {

    & {

        width: 200px;

        padding: 20px;

        background: #eee;

        border: 1px solid black;

    }

    > .content {

        background: #ddd;

    }

}

The second set of CSS selectors protects HTML elements styled without border-box in mind from layout disruption.

Reference:

https://www.toptal.com/front-end/eight-expert-css-tips 28 January 2021