CSS垂直中心图像和文本

时间:2013-07-09 21:29:14

标签: css

我写的这个源代码就是例如,我是手动输入padding-top 90px for h2 tag,例如我想要的;但删除填充文本时不垂直居中。当我知道bluebox div高度时这不是问题,但有时这是200px,有时是900px。

.bluebox
{
width: 400px;
background-color: blue;
height: 200px;
}

.bluebox h2
{
font-family: Arial;    
font-size: 10pt;  
text-align: center;
padding-top: 90px;
}

<div class="bluebox"><h2>Hi i am a text, now I am only horizontal centered<h2></div>

演示:http://jsfiddle.net/5UJWa/

5 个答案:

答案 0 :(得分:1)

.bluebox {
    width: 400px;
    background-color: blue;
    height: 200px;
    position: relative; /* allow absolute positioning within */
}

.bluebox h2 {
    font-family: Arial;    
    font-size: 10pt;  
    text-align: center;
    position: absolute; /* positioning */
    top: 50%; /* 50% from the top (half way) */
    margin-top: -5pt; /* bring it back up half the height of your text size */
    width: 100%; /* to allow for the text align */
}

http://jsfiddle.net/zTPgh/1/处的示例 - 更改容器的高度并运行或更新以查看其运行情况。

答案 1 :(得分:0)

您可以使用display: table-cell;

你的新CSS:

.bluebox {
    width: 400px;
    background-color: blue;
    height: 150px;
    display: table-cell;
    vertical-align: middle;
}

.bluebox h2 {
    font-family: Arial;    
    font-size: 10pt;  
    text-align: center;
}

Check out the illustration on jsFiddle.

答案 2 :(得分:0)

请参阅我的教程,它将垂直对齐并居中文本和图像。不要依赖行高,因为文本行之间会有很大的间隙。 http://www.andy-howard.com/verticalAndHorizontalAlignment/index.html

答案 3 :(得分:0)

我为垂直图像中心和文本创建了一个演示,我也测试了firefox,chrome,safari,Internet Explorer 9和8。

这是非常简短的css和html,请检查下面的代码,你可以在screenshort上找到输出。

<强> HTML

    <div class="frame">
      <img src="capabilities_icon1.png" alt="" />
    </div>

<强> CSS

    .frame {
        height: 160px;      
        width: 160px;
        border: 1px solid red;
        white-space: nowrap;
        text-align: center; margin: 1em 0;
    }

    .frame::before {
        display: inline-block;
        height: 100%;
        vertical-align: middle;
        content:"";
    }

    img {
        background: #3A6F9A;
        vertical-align: middle;
    }

enter image description here

答案 4 :(得分:0)

为了将元素垂直对齐,我使用了css3 calc()函数。它完全适用于所有最新的浏览器,包括ie11和edge。

点击此处https://jsfiddle.net/ashish_m/ebLxsxhk/

.calcTest { width: 250px; height: 250px; border:1px solid #e0e0e0; text-align: center; }
.calcTest .calcTestInner { width: 50px; height: 50px; background: #e0e0e0; 
margin: 0 auto; margin-top: calc(50% - 25px); vertical-align: top; }
<div class="calcTest">
  <div class="calcTestInner">
    Hello Folks
  </div>
</div>