文章目录
# display: flex
- 方便、直观
兼容性差
<style>
.out {
background-color: blueviolet;
width: 600px;
height: 300px;
display: flex;
}
.in {
background-color: yellowgreen;
width: 100px;
height: 100px;
align-self: center;
}
</style>
<div class="out">
<div class="in"></div>
</div>
或者
<style>
.out {
background-color: blueviolet;
width: 600px;
height: 300px;
display: flex;
align-items: center;
}
.in {
background-color: yellowgreen;
width: 100px;
height: 100px;
}
</style>
<div class="out">
<div class="in"></div>
</div>
或者
<style>
.out {
background-color: blueviolet;
width: 600px;
height: 300px;
display: flex;
}
.in {
background-color: yellowgreen;
width: 100px;
height: 100px;
margin: auto 0;
}
</style>
<div class="out">
<div class="in"></div>
</div>
# display: grid
和 flex 几乎一样,同样需要考虑兼容性问题
<style>
.out {
background-color: blueviolet;
width: 600px;
height: 300px;
display: grid;
align-items: center;
}
.in {
background-color: yellowgreen;
width: 100px;
height: 100px;
}
</style>
<div class="out">
<div class="in"></div>
</div>
或者
<style>
.out {
background-color: blueviolet;
width: 600px;
height: 300px;
display: grid;
}
.in {
background-color: yellowgreen;
width: 100px;
height: 100px;
margin: auto 0;
}
</style>
<div class="out">
<div class="in"></div>
</div>
# transform: translateY(-50%)
- 兼容性最好
- 繁琐
<style>
.out {
background-color: blueviolet;
width: 600px;
height: 300px;
position: relative;
}
.in {
background-color: yellowgreen;
width: 100px;
height: 100px;
position: absolute;
top: 50%;
-ms-transform: translateY(-50%); /*兼容性*/
transform: translateY(-50%);
}
</style>
<div class="out">
<div class="in"></div>
</div>
# display: table-cell
- 有 flex 方法了,这种方法感觉没必要:功能实现了,但语境感觉完全不对(for table?)
<style>
.out {
background-color: blueviolet;
width: 600px;
height: 300px;
display: table-cell;
vertical-align: middle;
}
.in {
background-color: yellowgreen;
width: 100px;
height: 100px;
}
</style>
<div class="out">
<div class="in"></div>
</div>
# ghost element
(实用,但感觉是时代的产物)
- 兼容性好
- 比较难理解
来源于这篇文章: https://css-tricks.com/centering-in-the-unknown/
实现方法有点像变魔术。
/* This parent can be any width and height */
.block {
text-align: center;
/* May want to do this if there is risk the container may be narrower than the element inside */
white-space: nowrap;
}
/* The ghost, nudged to maintain perfect centering */
.block:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
}
/* The element to be centered, can also be of any width and height */
.centered {
display: inline-block;
vertical-align: middle;
width: 300px;
}