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

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

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

当前回答

现在Flexbox的支持正在增加,这个CSS应用到包含元素将垂直居中所有包含的项目(除了那些指定对齐本身的项目,例如align-self:start)

.container {
    display: flex;
    align-items: center;
}

如果你还需要针对ie10和更老版本(< 4.4 (KitKat))的Android浏览器,请使用带前缀的版本:

.container {
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;

    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;
    align-items: center;
}

其他回答

就在这个:

<div>
    <table style="width: 100%; height: 100%">
        <tr>
            <td style="width: 100%; height: 100%; vertical-align: middle;">
               What ever you want vertically-aligned
            </td>
        </tr>
    </table>
</div>

一个单元表内的div处理垂直对齐和向后兼容回石器时代!

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

我一个朋友的一个技巧:

Div:前面{内容:" ";显示:inline-block;高度:100%;vertical-align:中间;} Div p{显示:inline-block;} < div风格= "高度:100 px;边界:1 px固体;" > < span style=" font - family:宋体;"</p> .我是垂直居中的 < / div >

演示。

在父div中创建中央子div的三种方法

绝对定位法 Flexbox方法 变换/翻译方法

Demo

/* Absolute Positioning Method */ .parent1 { background: darkcyan; width: 200px; height: 200px; position: relative; } .child1 { background: white; height: 30px; width: 30px; position: absolute; top: 50%; left: 50%; margin: -15px; } /* Flexbox Method */ .parent2 { display: flex; justify-content: center; align-items: center; background: darkcyan; height: 200px; width: 200px; } .child2 { background: white; height: 30px; width: 30px; } /* Transform/Translate Method */ .parent3 { position: relative; height: 200px; width: 200px; background: darkcyan; } .child3 { background: white; height: 30px; width: 30px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } <div class="parent1"> <div class="child1"></div> </div> <hr /> <div class="parent2"> <div class="child2"></div> </div> <hr /> <div class="parent3"> <div class="child3"></div> </div>

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

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