1. 水平居中
(1)是不是行內元素(inlin-*)精续?
主要使用text-align: center;
來實現(xiàn),例如:
header, nav {
text-align: center;
background: white;
margin: 20px 0;
padding: 10px;
}
<!-- HTML -->
<header>
This text is centered.
</header>
(2)是不是塊元素(block)婚脱?
塊元素(block-level element)今魔,要將它的margin-left
, margin-right
設置為auto
, 另外需要將它設置一個width:200px
勺像,否則它的寬度會占滿最大寬度 ,而這樣就沒有水平居中的必要了错森。
不管該塊元素或者其父元素寬度設置為多少吟宦,它都會生效。
.center-me { margin: 0 auto; }
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
body {
background: #f06d06;
}
main {
background: white;
margin: 20px 0;
padding: 10px;
}
.center {
margin: 0 auto;
width: 200px;
background: black;
padding: 20px;
color: white;
}
</style>
</head>
<body translate="no">
<main>
<div class="center">
I'm a block level element and am centered.
</div>
</main>
</body>
</html>
特別注意:不能通過float
一個元素來居中涩维⊙晷眨看這里 https://css-tricks.com/float-center/
(3)是不是多個塊元素?
如果你有兩個或多個塊級元素需要在一行中水平居中瓦阐,最好讓它們成為不同的display
類型辰狡。這是一個使它們成為inline-block
的例子和一個flexbox
的例子:
<main class="inline-block-center">
<div>
I'm an element that is block-like with my siblings and we're centered in a row.
</div>
<div>
I'm an element that is block-like with my siblings and we're centered in a row. I have more content in me than my siblings do.
</div>
<div>
I'm an element that is block-like with my siblings and we're centered in a row.
</div>
</main>
<main class="flex-center">
<div>
I'm an element that is block-like with my siblings and we're centered in a row.
</div>
<div>
I'm an element that is block-like with my siblings and we're centered in a row. I have more content in me than my siblings do.
</div>
<div>
I'm an element that is block-like with my siblings and we're centered in a row.
</div>
</main>
body {
background: #f06d06;
font-size: 80%;
}
main {
background: white;
margin: 20px 0;
padding: 10px;
}
main div {
background: black;
color: white;
padding: 15px;
max-width: 125px;
margin: 5px;
}
.inline-block-center {
text-align: center;
}
.inline-block-center div {
display: inline-block;
text-align: left;
}
.flex-center {
display: flex;
justify-content: center;
}
如果多個塊元素需要分多行居中顯示,這個時候使用前面的margin: 0 auto
是生效的垄分。
2. 垂直居中
垂直居中在CSS中是比較棘手的宛篇。
(1) 是不是行內元素? inline or inline-* elements (like text or links)
A. 是不是單行薄湿?
上下有相等的padding值叫倍,會讓它居中。
.link {
padding-top: 30px;
padding-bottom: 30px;
}
如果由于某種原因填充不是一個選項豺瘤,并且你試圖將一些你知道不會換行的文本居中吆倦,那么就有一個技巧是:使得line-height
等于height
。
B. 是不是多行坐求?
padding-top和padding-bottom的相等也可以為多行文本提供居中效果蚕泽。如果這不起作用,可能是因為文本元素在一個table cell
桥嗤,或者表面上通過CSS表現(xiàn)得像是一個table cell
须妻。
在這種情況下,vertical-align
屬性處理這個問題泛领,與處理行上對齊元素的對齊方式不同荒吏。
TODO......
(2) 是不是塊元素(block-level)?
A.知道元素的height
渊鞋?
B.不知道元素的height
绰更?
C.能用flex布局嗎 ?
這個就非常簡單了锡宋,直接使用列式布局方向:
.parent {
display: flex;
flex-direction: column;
justify-content: center;
}