CSS - 如何实现"左浮动"的混合效果和" text-align:center"?

时间:2016-04-17 14:06:16

标签: html css3

这是一个相当简单的问题,但我无法解决一个简单的解决方案。我需要连续居中3个方格,但我不知道平方的总数(虽然这个的简单解决方案是使用text-align: center),但我不想让最后的元素居中。简而言之,如何创建float: left效果+居中主容器内的所有元素?

JSfiddle here

HTML:

<div class="row b">
  <div class="col-lg-6 col-md-6 col-sm-12 col-lg-offset-3 col-md-offset-3">
    <div class="row maxW b">
      <div class="postContainer"></div>
      <div class="postContainer"></div>
      <div class="postContainer"></div>
      <div class="postContainer"></div>
    </div>
  </div>
</div>

CSS:

  .postContainer {
    width: 230px;
    height: 230px;
    border: 1px solid lightblue;
    display: inline-block;
  }

  .maxW {
    max-width: 900px;
  }

  .ce {
    text-align: center;
  }

.b{
  border:1px solid black;
}

预期结果:
这些方块应该是响应的,每行的最大方块是3.如果我使用float: left,我几乎得到了我需要的东西,但是方块被拉到左边而不是在主容器内居中。如果我使用text-align: center,方块在主容器中居中,但我不希望最后的方块居中,它们必须保持浮动到左侧。 enter image description here

3 个答案:

答案 0 :(得分:1)

我建议使用flexbox。它在css中是一个非常新的概念,但它有good support in all modern browsers。我个人在生产中使用它。

标记将简化为:

<div class="posts">
  <div class="postContainer"></div>
  <div class="postContainer"></div>
  <div class="postContainer"></div>
  <div class="postContainer"></div>
</div>

容器将有CSS:

.posts {
  display: flex;
  flex-flow: row wrap;
  justify-content: flex-start;
  margin: 0 auto;
}

Display: flex告诉浏览器它是一个flexbox,flex-flow表示它应该是完整时包裹的行,并且内容应该由flex-start左对齐。< / p>

Fiddle

Flexbox basics

答案 1 :(得分:0)

您可以将容器宽度设置为33%,然后在包含的div上设置帖子边框和宽度。

.postContainer {
  width: 33%;
  display: inline-block;
  text-align: center;
}

.post {
  width: 230px;
  height: 230px;
  border: 1px solid lightblue;
  display: inline-block;
}

https://jsfiddle.net/k9597cLq/

答案 2 :(得分:0)

您可以使用display:inline-block;代替float

你的CSS看起来像这样:

.maxW{
        border:1px solid black; 
        padding:5px;
      }

.postContainer{
               width:150px;
               height:150px;
               border:1px solid black; 
               display:inline-block; /* <-- the magic part*/
               }

DEMO