我有一个div与两个图像和一个h1。所有这些都需要在div中垂直对齐,彼此相邻。其中一个图像需要在div中绝对定位。
要在所有常见浏览器上工作,需要什么样的CSS ?
<div id="header">
<img src=".." ></img>
<h1>testing...</h1>
<img src="..."></img>
</div>
我有一个div与两个图像和一个h1。所有这些都需要在div中垂直对齐,彼此相邻。其中一个图像需要在div中绝对定位。
要在所有常见浏览器上工作,需要什么样的CSS ?
<div id="header">
<img src=".." ></img>
<h1>testing...</h1>
<img src="..."></img>
</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>
其他回答
我最喜欢的新方法是用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>
这招对我很管用:
.vcontainer {
min-height: 10em;
display: table-cell;
vertical-align: middle;
}
我使用了这段非常简单的代码:
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,结果都不会改变。
几乎所有的方法都需要指定高度,但通常我们没有任何高度。
这里有一个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
使用display flex,首先你需要包装你想对齐的项目的容器:
<div class="outdiv">
<div class="indiv">
<span>test1</span>
<span>test2</span>
</div>
</div>
然后在我的例子中应用下面的CSS内容来包装div或outdiv:
.outdiv {
display: flex;
justify-content: center;
align-items: center;
}