div容器中间的中心内容

时间:2014-03-04 18:12:23

标签: html css

我正在尝试创建一个“tile”(方块),其内容完美地位于其中间。

这是HTML

  <div class="tile-facebook">
    <h5>Facebook</h5>
    <div class="tile-notification">4</div>
    <h4>notifications</h4>
  </div>

和CSS

.tile-facebook{
  width:175px;
  height:175px;
  background: #3b5998 ;
  text-align: center;
  border-radius: 10px;
  border-style: solid;
  border-color: #ccc;
  border-width:1px;
  color: white;
}

.tile-notification{
  font-size:80px;
  font-weight:bold;
  padding:10px 0px;

}

我在块的中间有文本,但我希望它直接在中间,从顶部和底部使用相同的填充。想法?

3 个答案:

答案 0 :(得分:2)

您可能无法设置高度,但可以使用伪元素或额外元素从框的任何宽度绘制正方形。

100%+内联块的垂直填充是一种绘制正方形并在其中间添加内容的方法。

<div class="tile-facebook">
    <div class="wrapper">
        <h5>
            Facebook
        </h5>
        <div class=" tile-notification ">
            4
        </div>
         <h4>
             notifications
        </h4>
    </div>
</div>
.tile-facebook {
    width:175px;
    background: #3b5998;
    text-align: center;
    border-radius: 10px;
    border-style: solid;
    border-color: #ccc;
    border-width:1px;
    color: white;
}
.tile-notification {
    font-size:80px;
    font-weight:bold;
}
.tile-facebook .wrapper * {
    margin:0;
}
.tile-facebook:before {
    padding-top:100%;
    content:'';
}
.tile-facebook:before,
.wrapper {
    display:inline-block;
    vertical-align:middle;
}

http://jsfiddle.net/cnq82/

关于垂直%填充或边距的一些解释:http://www.w3.org/TR/CSS2/box.html#padding-properties&amp; http://www.w3.org/TR/CSS2/box.html#propdef-margin-top

所以,(希望它更明确一点:))

如果给出100%的垂直填充,其高度将等于父级的宽度。

如果您希望身高超过20px,您可以执行:padding:100% 0 20px 0 ;padding:20px 0 100% 0;

如果你想要一个比例为4:3的盒子,只需padding-top:75%;padding:50% 0 25% 0;

伪元素或额外元素可以是浮点数,也可以是内联块,用于垂直对齐。

您无需在父级CSS中设置宽度。

答案 1 :(得分:1)

此修复程序要求内容高度永远不会更改,您需要添加另一个<div>

<div class="tile-facebook">
  <div class="center">
    <h5>Facebook</h5>
    <div class="tile-notification">4</div>
    <h4>notifications</h4>
  </div>
</div>

添加CSS:

.title-facebook {
    position: relative;    
}

.center {
    position: absolute;
    top: 50%;
    margin-top: -[half height];
    left:0;
    width: 100%;
}

[half height]的高度是.center div的一半。

答案 2 :(得分:0)

在此处向您的CSS添加margin: -30px;

.tile-notification {
    font-size:80px;
    font-weight: bold;
    padding: 10px 0px;
    margin: -30px;
}
相关问题