以div为中心,所以它的内容总是在middel

时间:2016-12-02 08:34:25

标签: html css

我正试图将div {class =“informationbox”}居中,这样div的内部将始终以页面为中心,无论里面有多少div。

.informationbox{
  left: 0;
  right: 0;
  margin: 0 auto;
  display:block;
  position: absolute;
}
<div class="informationbox">
        <div style="display: inline-block;">
            <img src="https://c1.staticflickr.com/1/342/19541848580_7f925817c9_b.jpg" />
            <p>Something</p>
            <p>Wall of Text</p>
        </div>
        <div style="display: inline-block;">
            <img src="https://c1.staticflickr.com/1/342/19541848580_7f925817c9_b.jpg" />
            <p>Something</p>
            <p>Wall of Text</p>
        </div>
        <div style="display: inline-block;">
            <img src="https://c1.staticflickr.com/1/342/19541848580_7f925817c9_b.jpg" />
            <p>Something</p>
            <p>Wall of Text</p>
        </div>
</div>

2 个答案:

答案 0 :(得分:3)

只需将文本对齐中心添加到信息框并删除所有其他CSS。请注意,这仅适用,因为(所有)您的内容是内联的(您的div有display: inline-block)。

.informationbox{
   text-align: center;
}
<div class="informationbox">
        <div style="display: inline-block;">
            <img src="https://c1.staticflickr.com/1/342/19541848580_7f925817c9_b.jpg" />
            <p>Something</p>
            <p>Wall of Text</p>
        </div>
        <div style="display: inline-block;">
            <img src="https://c1.staticflickr.com/1/342/19541848580_7f925817c9_b.jpg" />
            <p>Something</p>
            <p>Wall of Text</p>
        </div>
        <div style="display: inline-block;">
            <img src="https://c1.staticflickr.com/1/342/19541848580_7f925817c9_b.jpg" />
            <p>Something</p>
            <p>Wall of Text</p>
        </div>
</div>

警告:使用此解决方案时,最终可能会在内联块元素之间留下不需要的空间。这是因为它们之间存在“空间”(字符)。这可以通过在关闭前一个div后立即打开下一个div来解决。

答案 1 :(得分:1)

.informationbox{
  left: 0;
  right: 0;
  margin: 0 auto;
  display:block;
  position: absolute;
  display: flex;
  justify-content: space-around; /*or "center"*/
}
<div class="informationbox">
        <div style="display: inline-block;">
            <img src="https://c1.staticflickr.com/1/342/19541848580_7f925817c9_b.jpg" />
            <p>Something</p>
            <p>Wall of Text</p>
        </div>
        <div style="display: inline-block;">
            <img src="https://c1.staticflickr.com/1/342/19541848580_7f925817c9_b.jpg" />
            <p>Something</p>
            <p>Wall of Text</p>
        </div>
        <div style="display: inline-block;">
            <img src="https://c1.staticflickr.com/1/342/19541848580_7f925817c9_b.jpg" />
            <p>Something</p>
            <p>Wall of Text</p>
        </div>
</div>