将容器中的div内容居中

时间:2015-05-17 17:06:57

标签: javascript html css web

在我的网站上,我有一系列像这样的div:

(
  SELECT 1 subscribed, p.*
    FROM posts p JOIN subscribed s
      ON p.id = s.post_id
   WHERE p.title LIKE 'keyword%'
   ORDER BY title DESC
   LIMIT 10
)
UNION ALL
(
  SELECT 0 subscribed, p.*
    FROM posts p LEFT JOIN subscribed s
      ON p.id = s.post_id
   WHERE s.post_id IS NULL
     AND p.title LIKE 'keyword%'
   ORDER BY title DESC
   LIMIT 10
)
LIMIT 10

这些div位于一个简单的容器中,如下所示:

.box{
   float:left;
   width:143px;
   height:183px;
   overflow:hidden;
}

我会意识到响应式布局,但div在容器中不是水平居中的。我试图添加" margin-left:auto;" " margin-right:auto"但没什么。我有这样的布局:

enter image description here

相反,我会这样布局:

enter image description here

有人能帮助我吗?

4 个答案:

答案 0 :(得分:2)

使用FlexBox的解决方案。

<强> FlexBox Guide

<强> FlexBox Browsers Compatibility

.container {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-around;
  
    margin:7px 19px 0 19px;
    background-color: red;
}

.box {
    width:143px;
    height:183px;
    margin: 10px;
    background-color: black;
}
<div class="container">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</div>

答案 1 :(得分:1)

请参阅此fiddle

您可以使用display:inline-block;实现此目的,所以请删除CSS中使用的float:left

我做了如下例子,

<强> HTML

<div class="container">
    <div class="div1">
    </div>
    <div class="div1">
    </div>
    <div class="div1">
    </div>
    <div class="div1">
    </div>
</div>

<强> CSS

.div1{
    margin:10px;
    width:25%;
    height:100px;
    display:inline-block;
    background-color:red;
}

答案 2 :(得分:0)

使用float无法实现此目的。您可以使用display: inline-block

.box{
    width:143px;
    height:183px;
    overflow:hidden;
    display: inline-block;
}
.container{
    margin:70px 190px 0 190px;
    overflow:hidden;
    text-align: center;
}

答案 3 :(得分:0)

&#13;
&#13;
*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

.container{  
    overflow: hidden;
    max-width: 500px;
    margin: 0 auto;
}
.box{
    float:left;
    width: 31%;
    height: 183px;  
    background: #f00;
    margin: 1%;
}
&#13;
<div class="container">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</div>
&#13;
&#13;
&#13;