Solo Solo - 1 month ago 16
CSS Question

Span leaks outside of its parent elements

Span tags leak outside of its direct parent and all other wrapping parents too. Take a look at this fiddle.

I've tried

display
,
overflow
and other properties but I can't figure this out. It just keeps leaking out.

How to fix that?



.tag {
padding: 2px 5px 3px 5px;
margin-right: 5px;
border: 1px solid red;
white-space: nowrap; /* prevent splitting spans */
}

.tag-wrapper {
border: 1px solid blue;
max-width: 300px;
}

.parent {
border: 1px solid green;
}

<div class="parent">
<div class="tag-wrapper">
<span class="tag">tag 1</span>
<span class="tag">tag 2</span>
<span class="tag">tag 3</span>
<span class="tag">tag 4</span>
<span class="tag">tag 5</span>
<span class="tag">tag 6</span>
<span class="tag">tag 7</span>
</div>
</div>





I tried to find an answer but it seems that I don't know how to phrase this question. Im familiar with collapsing margins and it seems to be a different problem.

Answer

You're probably looking for display: inline-block;.

<span> elements by nature are an inline element, so their effective height is actually based on their content, rather than their bounding box. By making it behave as a block element, you should achieve your desired effect.

Here is an updated version of your fiddle, and here is the updated tag CSS:

.tag {
  padding: 2px 5px 3px 5px;
  margin-right: 5px;
  border: 1px solid red;
  white-space: nowrap; /* prevent splitting spans */
  display: inline-block;
}