在高度为百分比的div中居中文本

时间:2014-07-02 14:49:04

标签: html css

我有div,身高和宽度为33.33%。我希望文本位于div

的中间

HTML

<div class="blogs" id="content">
  <div id="blog1">tests</div>
  <div id="blog2"></div>
  <div id="blog3"></div>
</div>

CSS

#blog1 {
  width: 33.33%;
  padding-bottom: 33.33%;
  background: red;
  float: left;
}

enter image description here 我该怎么做?

3 个答案:

答案 0 :(得分:1)

我建议:

<强> HTML

<div class="blogs" id="content">
    <div id="blog1">text in the middle
        <span>blog 1</span>
    </div>
   <div id="blog2"><span>blog 2</span></div>
   <div id="blog3"><span>blog 3</span></div>
</div>

<强> CSS

 #blog1{
        width: 33.33%;
        /*padding-bottom: 33.33%;*/
        background: red;
        text-align: center;
        display:table-cell;
        vertical-align:middle;
        position: relative;
    }

.blogs > div > span{
    position: absolute;
    bottom: 0px;
    width: 100%;
    left: 0px;
}
 #blog2{
        width: 33.33%;
        padding-bottom: 33.33%;
        background: green;
        text-align: center;
        display:table-cell;
        position: relative;
    }
 #blog3{
        width: 33.33%;
        padding-bottom: 33.33%;
        background: blue;
        text-align: center;
        display:table-cell;
        position: relative;
    }

#content{
    display:table;
}

fiddle

静态宽度的另一个例子,例如500px fiddle

答案 1 :(得分:1)

看一下 fiddle

只需设置heightline-height相等即可添加vertical-align:middle;

您的代码如下所示:

#blog1{
    width: 33.33%;
    height:300px;
    background: red;
    float: left;
    text-align:center;
    vertical-align:middle;
    line-height:300px; /* has to bee the same value as the height of the div */
}

答案 2 :(得分:0)

<div class="blogs" id="content">
   <div id="blog1">tests</div>
   <div id="blog2"></div>
   <div id="blog3"></div>

   <!-- You need to add this after the last <div> -->
   <div style="clear:right;"></div>
</div>

#blog1, #blog2, #blog3 {
   float:left;
   padding: 3% 0;
   background: red;
   width: 100px;
   height:100%;
   text-align:center;
}

JS Fiddle