0

这真让我抓狂。我对这些东西比较陌生,所以在过去的一个小时里试图弄清楚这个。如果有人可以帮助我,我将非常感激。

我有以下代码:

<div class="middle_box">
     <div class="box left">
          Some large text
     </div>
     <div class="box right">
          Some large text as well
     </div>
</div>

CSS:

.middle_box {
    height: 260px;
    margin: 0 auto;
    width: 960px;
}
.box {
    float: left;
    font-size: 21px;
    margin-right: 50px;
    margin-top: 25px;
    padding-top: 25px;
    width: 390px;
}

如您所知,容器的宽度为 960 像素。现在,我想在 960px 容器中将两个 .box 元素居中,这就是我迷路的地方。

我尝试了什么?

我尝试使用margin: 0px auto;并尝试通过在两侧添加 margin-left 来伪造它,但它只是没有用。我怎样才能做到这一点?

4

5 回答 5

1

您需要清除“.middle_box”,因为它的子元素是浮动的。

.middle_box:before, .middle_box:after {
    content: "";
    display: table;
}
.middle_box:after { clear: both; }

应该做的伎俩

于 2013-09-13T01:09:54.203 回答
1

使用此 hack 的最佳方法调用 clearfix :

.middle_box:after {
        visibility: hidden;
        display: block;
        content: "";
        clear: both;
        height: 0;
        }
于 2013-09-13T01:10:04.517 回答
1

无论如何,当您使用固定宽度时960px390px为什么不设置边距呢?易于计算,在这种设置中不需要高级 CSS“魔法”。

.middle_box {
    height: 260px;
    margin: 0 auto;
    width: 960px;
    background-color: red;
}
.box {
    float: left;
    font-size: 21px;
    margin-left: 60px; /* <--- */
    margin-top: 25px;
    padding-top: 25px;
    width: 390px;
    background-color: yellow;
}

在此处输入图像描述

于 2013-09-13T01:19:34.953 回答
0

这是一个小提琴

HTML

带浮动 - 不同尺寸

<div class="middle_box">
  <div class="box0 left">
      Some large text
  </div>
  <div class="box0 right">
      Some large text as well
  </div>
</div>

没有浮动 - 相同的尺寸

<div class="middle_box">
  <div class="box1">
      Some large text
  </div>
  <div class="box1">
      Some large text as well
  </div>
</div>

清晰 - 一个在另一个之上

<div class="middle_box">
  <div class="box2 clear">
      Some large text
  </div>
  <div class="box2 clear">
      Some large text as well
  </div>
</div>

CSS

.middle_box {
  margin: 0 auto 10px;
  width: 960px;
  height: 260px;
  text-align: center;
  text-transform: uppercase;
  border: 1px solid #333;
}
.box0 {
  font-size: 21px;
  padding-top: 25px;
  height: 65px;
  border: 1px solid #333;
}
.left {
  float: left;
  width: 585px;
  margin: 24px 6px 0 24px;
}
.right {
  float: right;
  width: 300px;
  margin: 24px 24px 0 6px;
}
.box1 {
  float: left;
  font-size: 21px;
  margin-top: 25px;
  margin-left: 25px; /* margin-left | calculate 960px - boxes width - borders */
  padding-top: 25px;
  height: 65px;
  width: 438px;
  border: 1px solid #333;
}
.box2 {
  font-size: 21px;
  margin: 25px auto 25px;
  padding-top: 25px;
  width: 442px;
  height: 65px;
  border: 1px solid #333;
}
.clear {
  clear: both;
}
于 2013-09-13T01:11:10.280 回答
0

居中浮动很难,但你需要使用浮动吗?为什么不使用:

display: inline-block

使用两者都有优点/缺点floatinline-block并且两者都有其怪癖,但最终我发现 inline-block 更有用且更易于开发。这是解决您的问题的小提琴inline-block

演示小提琴

如果您确实使用它(但很容易修复),请注意它的空白怪癖:

http://css-tricks.com/fighting-the-space-between-inline-block-elements/

于 2013-09-13T08:31:15.497 回答