我有一个div与两个图像和一个h1。所有这些都需要在div中垂直对齐,彼此相邻。其中一个图像需要在div中绝对定位。

要在所有常见浏览器上工作,需要什么样的CSS ?

<div id="header">
  <img src=".." ></img>
  <h1>testing...</h1>
  <img src="..."></img>
</div>

当前回答

 .outer {
   display: flex;
   align-items: center; 
   justify-content: center;
 }

其他回答

我使用了这段非常简单的代码:

Div.ext-box{显示:表;宽度:100%;} Div.int-box{显示:表单元;vertical-align:中间;} < div class = " ext-box”> < div class = " int-box”> 一些txt < h2 > < / h2 > <p>bla bla bla</p> < / div > < / div >

显然,无论您使用.class还是#id,结果都不会改变。

我已经使用以下解决方案(没有定位和线高)一年多了,它适用于Internet Explorer 7和Internet Explorer 8。

<style>
.outer {
    font-size: 0;
    width: 400px;
    height: 400px;
    background: orange;
    text-align: center;
    display: inline-block;
}

.outer .emptyDiv {
    height: 100%;
    background: orange;
    visibility: collapse;
}

.outer .inner {
    padding: 10px;
    background: red;
    font: bold 12px Arial;
}

.verticalCenter {
    display: inline-block;
    *display: inline;
    zoom: 1;
    vertical-align: middle;
}
</style>

<div class="outer">
    <div class="emptyDiv verticalCenter"></div>
    <div class="inner verticalCenter">
        <p>Line 1</p>
        <p>Line 2</p>
    </div>
</div>

对我来说,它是这样工作的:

<div style="width:70px; height:68px; float:right; display: table-cell; line-height: 68px">
    <a href="javascript:void(0)" style="margin-left: 4px; line-height: 2" class="btn btn-primary">Login</a>
</div>

“a”元素转换为按钮,使用Bootstrap类,它现在垂直居中在一个外部的“div”。

我的技巧是在div里面放一个表,一行一列,设置100%的宽度和高度,属性vertical-align:middle:

<div>

    <table style="width:100%; height:100%;">
        <tr>
            <td style="vertical-align:middle;">
                BUTTON TEXT
            </td>
        </tr>
    </table>

</div>

小提琴: http://jsfiddle.net/joan16v/sbqjnn9q/

我们可以使用CSS函数计算来计算元素的大小,然后相应地定位子元素。

示例HTML:

<div class="box">
    <span><a href="#">Some Text</a></span>
</div>

和CSS:

.box {
    display: block;
    background: #60D3E8;
    position: relative;
    width: 300px;
    height: 200px;
    text-align: center;
}

.box span {
    font: bold 20px/20px 'source code pro', sans-serif;
    position: absolute;
    left: 0;
    right: 0;
    top: calc(50% - 10px);
}

a {
    color: white;
    text-decoration: none;
}

演示创建在这里:https://jsfiddle.net/xnjq1t22/

这个解决方案工作良好的响应div高度和宽度以及。

注意:没有测试calc函数与旧浏览器的兼容性。