htmlcssborder-box

Giving two inline-block elements a 50% width using the box-sizing property


I have a parent div that has a padding of 20px. Inside this div there are two span tags. I'd like their width to be 50% of the parent div and fit on the same line. box-sizing: border-box didn't seem to fix the issue.

HTML

<div>
  <span>foo</span>
  <span>bar</span>
</div>

CSS

div {
  border: 1px solid black;
  box-sizing: border-box;
  padding: 20px;
  width: 150px;
}

div span {
  box-sizing: border-box;
  border: 1px solid green;
  display: inline-block;
  width: 50%;
}

UPDATE:

It looks like box-sizing wasn't necessary for this use-case and CBroe's answer solves the problem accordingly.


Solution

  • The white space between the elements is your problem.

    inline-block elements are laid out pretty much like normal text, and so the white space between one element’s closing and the next element’s opening tag gets condensed to one single space character according to general HTML rules – and that makes 50% + one space character + 50% end up being a little more than 100%, and so the second element breaks into a new “line”

    There are several ways to try and fight this – from eliminating the white space between the element’s tags, setting font-size to 0 for everything “outside” those elements … Some of them are discussed in more detail here: http://css-tricks.com/fighting-the-space-between-inline-block-elements/