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

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

<div id="header">
  <img src=".." ></img>
  <h1>testing...</h1>
  <img src="..."></img>
</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/

其他回答

我发现了一个新的解决方案,垂直对齐多个文本行在一个div使用CSS 3(我也使用bootstrap v3网格系统来美化UI),如下所示:

.immediate-parent-of-text-containing-div {
    height: 50px;         /* Or any fixed height that suits you. */
}

.text-containing-div {
    display: inline-grid;
    align-items: center;
    text-align: center;
    height: 100%;
}

根据我的理解,包含元素的文本的直接父元素必须有一定的高度。

使用这个公式,它将永远没有裂缝:

#outer {height: 400px; overflow: hidden; position: relative;} #outer[id] {display: table; position: static;} #middle {position: absolute; top: 50%;} /* For explorer only*/ #middle[id] {display: table-cell; vertical-align: middle; width: 100%;} #inner {position: relative; top: -50%} /* For explorer only */ /* Optional: #inner[id] {position: static;} */ <div id="outer"> <div id="middle"> <div id="inner"> any text any height any content, for example generated from DB everything is vertically centered </div> </div> </div>

我最喜欢的新方法是用CSS网格:

/* technique */ .wrapper { display: inline-grid; grid-auto-flow: column; align-items: center; justify-content: center; } /* visual emphasis */ .wrapper { border: 1px solid red; height: 180px; width: 400px; } img { width: 100px; height: 80px; background: #fafafa; } img:nth-child(2) { height: 120px; } <div class="wrapper"> <img src="https://source.unsplash.com/random/100x80/?bear"> <img src="https://source.unsplash.com/random/100x120/?lion"> <img src="https://source.unsplash.com/random/100x80/?tiger"> </div>

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

只使用Bootstrap类:

Div: class="容器d-flex" div中的元素:class="m-auto"

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css" crossorigin="anonymous"> < span class=" font - family:宋体" style=" font - family:宋体;background - color: # 333;" > < h2 class = " m-auto " > < a href = " https://hovermind.com/ " > H➲版本➾M⇡ND < / > < / h2 > < / div >