http://jsfiddle.net/gLfw5wc7/3/
#testData {
padding:4px;
width: 100%;
border: 1px solid #999;
background: #d1d1d1;
text-align:right;
}
#testData:after {
content:"";
clear: both;
display: table;
}
#testData > span {
padding: 3px 1px 1px;
float:left;
}
This is known as a clearfix. When floating an element, it gets out "the flow" of the document. This also means that its width and height aren't taken into account by the parent. That's why #testData
seems to collapse: it thinks it doesn't have content. To fix this there are some options. The easiest is to use overflow
, however, that's bad practice imo. In this particular case it works, but in some other cases you won't be able to use it because content that overflows the parent will either be hidden (overflow: hidden
) or a scrollbar will appear (overflow: auto
).
The most common and proper solution is to use a pseudo element to fix this. :after
is such a pseudo element (see this question for :after
vs ::after
). Basically, a pseudo element can create an element in CSS that is not visible in HTML.
Every time you use float
, you'll be needing a clearfix. Therefore it's useful to create a .clear
class which you can apply to every element that needs to clear floats. It would look like this.
HTML
<div id="testData" class="clear">
<span>
TestData: Float Left
</span>
</div>
CSS
.clear:after {
content:"";
clear: both;
display: table;
}
Now you can add class="clear"
to every element that needs to be cleared. If you are into SASS, you might find this answer helpful but considering you are new to HTML, I'd suggest sticking to HTML and CSS first.