如何在容器中浮动元素 [英] How to float elements inside a container

查看:35
本文介绍了如何在容器中浮动元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将 #container 放置在屏幕中央,并将图表" float:left 放置在 #container .

I am trying to put the #container in the center of the screen and make the 'charts' float:left inside the #container.

但是使用下面的代码,图表"位于 #container 下.谁能告诉我如何更改代码?并告诉我为什么代码会在 #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>

推荐答案

在将float添加到元素时,您的文档自然流失了.

When you add float to an element you're taking out of the natural flow of the document.

您将需要在浮动项的包装中添加某种clearfix.

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>

更新

如果宽度固定,为什么要使div浮动?

If the width is fixed why would you float the divs?

这篇关于如何在容器中浮动元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆