【问题标题】:Center Overflowed Floated Divs in a Container容器中的中心溢出浮动 div
【发布时间】:2014-07-01 17:09:20
【问题描述】:

我目前有一个简单的设置:一个居中的容器 div,它是屏幕宽度的 90%,包含五个 20% 宽度的 div。当 div 都适合在行上时,这很有效。它们都进行了调整,以使它们均匀分布并居中。但是,由于 5 个 div 必须具有最小宽度,因此当用户将屏幕调整为较小的宽度时,它们会填充多于一行并且不再居中。一旦发生这种情况,我希望它们保持最小宽度,但要居中,以便您可以在 div 的顶行的任一侧看到蓝色容器 div,而不是让它们全部左对齐(对于以下行也是如此)。我怎样才能在 HTML 和 CSS 中做到这一点?谢谢。

<style type="text/css">
.container {
  height: 220px;
  width: 90%;
  max-width: 1200px;

  margin-left: auto;   
  margin-right: auto;

  background-color: blue;
}

.box {
  position: relative;
  height: 100%;
  width: 20%;
  min-width: 200px;

  margin: 0 auto;
  float: left;

  background-color: red;
}
</style>


<div class="container">
    <div class="box">1</div>
    <div class="box">2</div>
    <div class="box">3</div>
    <div class="box">4</div>
    <div class="box">5</div>
</div> 

【问题讨论】:

    标签: html css


    【解决方案1】:

    如果你不使用浮点数,而是使用display:inline-blocktext-align:center,我想你会得到你想要的居中效果。

    .container 
    {
        text-align:center;
    }
    
    .box 
    {
        display:inline-block;
        /*For IE*/
        *display: inline;
        zoom:1;
        /*Aligns divs vertically along the top*/
        vertical-align:top;
    }
    

    此处示例:

    http://jsfiddle.net/DigitalBiscuits/pXGz3/3/

    (调整结果窗口大小看效果)

    注意:使用 inline-block 时,请确保&lt;div&gt;s 之间没有回车。否则你会在它们之间得到一点不需要的空间

    【讨论】:

    • 谢谢。这让我的大部分方式都在那里,但是一旦我开始添加内容,这些框就不再垂直对齐了。 (e.i div class="box"&gt;1&lt;/div&gt;&lt;div class="box"&gt;2 &lt;br&gt; &lt;br&gt; 2&lt;/div&gt;&lt;div class="box"&gt;3&lt;/div&gt;&lt;div class="box"&gt;4&lt;/div&gt;&lt;div class="box"&gt;5&lt;/div&gt; ) 我能做些什么来避免这种情况?
    • 哦,对了,对不起...我已经编辑了我的答案以解决这个问题,以及一个 IE 错误。垂直对齐的额外 CSS 是 vertical-align:top 并且有两行额外的行可以使 div 在 IE8 及更低版本中正常运行。希望这对你有用。
    猜你喜欢
    • 1970-01-01
    • 2016-05-04
    • 2021-06-04
    • 2014-09-09
    • 1970-01-01
    • 2016-06-15
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多