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

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

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

当前回答

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

#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>

其他回答

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
    <head>
        <style type="text/css">
            #style_center { position:relative; top:50%; left:50%; }
            #style_center_absolute { position:absolute; top:50px; left:50px; }
            <!--#style_center { position:relative; top:50%; left:50%; height:50px; margin-top:-25px; }-->
        </style>
    </head>

    <body>
        <div style="height:200px; width:200px; background:#00FF00">
            <div id="style_center">+</div>
        </div>
    </body>
</html>

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

<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”。

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

#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>

几乎所有的方法都需要指定高度,但通常我们没有任何高度。

这里有一个css3的三行技巧,它不需要知道高度。

.element {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

甚至在IE9中也支持它。

与其供应商前缀:

.element {
    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}

来源:垂直对齐任何只需3行CSS

只使用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 >