Div height does not resize when add more content
I'm trying to build a kind of tag-cloud
.
I've a div (the tag container) in which dinamically I add span nodes (the tags).
span
nodes are default inline elements, so if I've set their display
property do display:block
, to prevent that they will overflow the div horizontally.
I've also set their float
property to float:left
since I want that they're disposed near on the same line and if line is full tthey automatically go to the next line.
The problem now开发者_高级运维 is that, the tags overflow vertically on the bottom. The tag container does not resize its height to contain all the tags inserted. How could I fix this problem?
EDIT Here is the fiddle. http://jsfiddle.net/Vk92s/1/
As you can see, if a comment float: left
, the div automatically resize, but all the tags dispose on a new line.
At opposite, if i add the float: left
, the tags wrap correctly, but div does not resize.
Here's a fiddle.
You can set overflow
to hidden
, like below:
<div id="test">
<span>first</span>
<span>second </span>
<span>third </span>
<span>fourth </span>
</div>
#test
{
border: 1px solid black;
width: 100px;
overflow: hidden;
}
span
{
float: left;
}
In your tag container div, add this css rule:
overflow: auto;
This will make it expand to contain its floated content.
Edit:
A fiddle: http://jsfiddle.net/5AgxU/
Try adding a div that has clear: both
set under all of your elements.
Working Demo
HTML
<div id="tag-cloud">
<span class="tag">example</span>
<span class="tag">example</span>
<span class="tag">example</span>
<span class="tag">example</span>
<span class="tag">example</span>
<span class="tag">example</span>
<span class="tag">example</span>
<span class="tag">example</span>
<div class="clear-both"></div>
</div>
CSS
.tag{
display: block;
width: 98px;
background-color: red;
margin-right: 2px;
float: left;
}
.clear-both{
clear: both;
}
#tag-cloud{
width: 300px;
background-color: black;
}
Rather than adding an empty element that clears your float, my preference is to use the following on the parent element so you don't pollute your markup.
.clearfix:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
.clearfix {
display: inline-block;
}
html[xmlns] .clearfix {
display: block;
}
* html .clearfix {
height: 1%;
overflow: visible;
}
精彩评论