0

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

.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/

4

5 回答 5

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/上的示例- 更改容器的高度并运行或更新以查看它的运行情况。

于 2013-07-09T21:48:53.323 回答
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;
}

查看 jsFiddle 上的插图。

于 2013-07-09T21:34:32.463 回答
0

在此处查看我的教程,它将垂直对齐和居中文本和图像。不要依赖行高,因为文本行之间会有很大的差距。http://www.andy-howard.com/verticalAndHorizo​​ntalAlignment/index.html

于 2013-07-10T07:25:28.630 回答
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>

于 2016-11-04T05:33:00.513 回答
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;
    }

在此处输入图像描述

于 2015-12-03T13:01:58.800 回答