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

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

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

当前回答

我已经使用以下解决方案(没有定位和线高)一年多了,它适用于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:前面{内容:" ";显示:inline-block;高度:100%;vertical-align:中间;} Div p{显示:inline-block;} < div风格= "高度:100 px;边界:1 px固体;" > < span style=" font - family:宋体;"</p> .我是垂直居中的 < / div >

演示。

要将块元素定位到中心(适用于Internet Explorer 9及以上版本),它需要一个包装器div:

.vcontainer {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
}
 .outer {
   display: flex;
   align-items: center; 
   justify-content: center;
 }

我们可以使用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函数与旧浏览器的兼容性。

这招对我很管用:

.vcontainer {
    min-height: 10em;
    display: table-cell;
    vertical-align: middle;
}