调整大小时将两个框居中

Centering two boxes on resize

我想知道是否有人对如何最好地在调整页面大小时强制两个 div 居中提出建议。

这里是相关的 html:

<div id="body">
    <div id="top"></div>
    <div id="content">
        <div id="box1"></div>
        <div id="box2"></div>
    </div>
   <div id="footer"></div>
</div>

我通常希望框 1 和框 2 div 与彼此的 left and right 对齐。所以我使用以下 CSS:

#box1, #box2
    {
        float:left;
        max-width:25em;
        min-width:20em;
        width:45%;
    }

我要解决的问题是如何最好地让它们堆叠,然后在调整页面大小时居中。所需的外观是:

我知道我会使用这样的媒体查询:

@media screen and (max-width: 800px)
    { 
        #box1, #box2
            {
                /* SOMETHING */
            }
    }

应将以下内容放入您的媒体查询中:

  • 要阻止它们相互堆叠,您需要移除 float: left;。这是因为 divblock 元素,会自动换行
  • 您给 divs width 所以添加 margin: 0 auto; 将使它们居中

#box1 {
  background-color: red;
}
#box2 {
  background-color: blue;
}
#box1, #box2 {
  float: left;
  max-width: 25em;
  min-width: 20em;
  width: 45%;
}
@media screen and (max-width: 800px) {
  #box1, #box2 {
    float: none;
    margin: 0 auto;
    max-width: 25em;
    min-width: 20em;
    width: 45%;
  }
}
<div id="box1">Box 1</div>
<div id="box2">Box 2</div>

这里不需要媒体查询。

试试这个。

#content {

    text-align: center;
    display:inline-block;
    border:thick dotted #060;
    margin: 0px auto 10px auto;
    width:100%;
}

#box1,
#box2
 {

    max-width:25em;
    min-width:20em;
    width:45%;
    height: 50px;
    background: #999;
    display: inline-block;
  }

Demo here