问题
I am trying to put the #container
in the center of the screen and make the 'charts' float:left
inside the #container
.
But with the code I have below, the 'charts' locate under the #container
. Can anyone tell me how can I change the code? And tell me why the code make the 'charts' outside the #container
.
#container {
margin: auto;
width: 10%;
border: 3px solid #73AD21;
padding: 10px;
}
#id1,
#id2,
#id3,
#id4 {
float: left;
font-size: 30px;
}
<div id="container">
<div id="id1">
<p>chart1</p>
</div>
<div id="id2">
<p>chart2</p>
</div>
<div id="id3">
<p>chart3</p>
</div>
<div id="id4">
<p>chart4</p>
</div>
</div>
回答1:
When you add float to an element you're taking out of the natural flow of the document.
You will need to add some sort of clearfix to the wrapper of the floated items.
.clearfix:before,
.clearfix:after {
content: "";
display: table;
}
.clearfix:after {
clear: both;
}
#container{
margin: auto;
width: 10%;
border: 3px solid #73AD21;
padding: 10px;
}
#id1,
#id2,
#id3,
#id4 {
float:left;
font-size: 30px;
}
<div id="container" class="clearfix">
<div id="id1"><p>chart1</p></div>
<div id="id2"><p>chart2</p></div>
<div id="id3"><p>chart3</p></div>
<div id="id4"><p>chart4</p></div>
</div>
UPDATE
If the width is fixed why would you float the divs?
回答2:
whenever you float
you need to clear the float
items, plus use classes instead of ID's if you are applying the same attributes.
Increase the width
for your container in order to have 2 items per row as stated in your comment above
.cf:before,
.cf:after {
content: "";
display: block;
}
.cf:after {
clear: both;
}
#container {
margin: auto;
width: 24%; /* to have 2 divs per row */
border: 3px solid #73AD21;
padding: 10px;
}
.float {
float: left;
font-size: 30px;
}
<div id="container" class="cf">
<div class="float">
<p>chart1</p>
</div>
<div class="float">
<p>chart2</p>
</div>
<div class="float">
<p>chart3</p>
</div>
<div class="float">
<p>chart4</p>
</div>
</div>
来源:https://stackoverflow.com/questions/35992894/how-to-float-elements-inside-a-container