Carl Edwards
Carl Edwards

Reputation: 14434

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.

Upvotes: 0

Views: 1841

Answers (2)

C3roe
C3roe

Reputation: 96306

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/

Upvotes: 4

Adam Jenkins
Adam Jenkins

Reputation: 55623

There's a 100 ways to do this (maybe exaggeration, but I can think of at least 4).

Easiest way is to make them block elements (borders added for clarity):

* { box-sizing: border-box; }
span { display: block; width: 50%; float: left; padding: 12px; text-transform: uppercase; border: 4px solid #000; background: #f00;}
div { border: 2px solid #0f0; overflow:hidden;}
<div>
  <span>first span</span>
  <span>second span</span>
</div>

Upvotes: 0

Related Questions