How do I keep the buttons a full 50% of the element?

If I keep the button and container sizes as is below, the buttons fit the element exactly 50% and resize accordingly. But if I add a 1px border, all bets are off – they all become stacked, and I can’t figure out how to get the buttons back to 50% of the element so they line up side by side.

How do I get bordered button divs to be 50% of the container element and line up side by side?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="description" content="">
<!-- Set the viewport width to device width for mobile -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Test</title>
    <style type="text/css">
        #nav {width:100%; margin:0;padding:0;background-color:yellow;}
        .navbutton {width:50%; margin:0; background-color:red; float:left; font-size:1em; line-height: 2em;}
    </style>
</head>
<body>
    <div id="nav">
        <a href="index.html"><div class="navbutton">Home</div></a>
        <a href="index.html"><div class="navbutton">Home</div></a>
        <a href="index.html"><div class="navbutton">Home</div></a>
        <a href="index.html"><div class="navbutton">Home</div></a>
    </div>
</body>
</html>

Eventually, I’d like these 4 buttons to go all the way across, 25%.

Borders are applied outside the element, so as soon as you add a border to an item that is 50% wide, it becomes > 50% + the width of the element.

You can reduce the size to say 49%, which would make it very close.

Hi, StevenHu.

Probably the most common way to add a border to a 25% box without upsetting the percent width is to use the {box-sizing:border-box} property.

*, *:before, *:after {
    -webkit-box-sizing:border-box;
    -moz-box-sizing:border-box;
    box-sizing:border-box;
}

Here are two articles about it:

http://www.paulirish.com/2012/box-sizing-border-box-ftw/

1 Like

Another alternative would be to use calc()

.navbutton {width: calc(25% - 2px); ...
1 Like

Both of these ideas are awesome contributions! Thanks. Works in IE, FF, Chrome, iPod, and Android Nexus 7!