CSS中水平居中的方法
水平居中:
1. 是inline元素还是inline-*元素(如文本或链接)?
使用 text-align:center水平居中父元素中内嵌元素;这将适用于内联(inline),内联块(inline-block),内联表(inline-table),内联弹性(inline-flex)等
html
<header>
This text is centered.
</header>
<nav role='navigation'>
<a href="#0">One</a>
<a href="#0">Two</a>
<a href="#0">Three</a>
<a href="#0">Four</a>
</nav>
css:
body {
background: #f06d06;
}
header, nav {
text-align: center;
background: white;
margin: 20px 0;
padding: 10px;
}
nav a {
text-decoration: none;
background: #333;
border-radius: 5px;
color: white;
padding: 3px 8px;
};
2 是block块级元素吗?
使用 margin:0 auto,给需要居中的块级元素设置width,否则是全宽的;不能使一个带有float属性的元素居中,使用这种方法。
html:
<main>
<div class="center">
I'm a block level element and am centered.
</div>
</main>
css:
main {
background: white;
margin: 20px 0;
padding: 10px;
}
.center {
margin: 0 auto;
width: 200px;
background: black;
padding: 20px;
color: white;
}
3 多个块级元素?
需要水平居中在一行上面,方法是使它们有不同的display类型
flex布局的居中是:justify-content: center
html:
//一个是display:inline-block
<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>
//一个是display:flex 居中是:justify-content: center;
<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>
CSS:
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 {
//设置 了这个属性,块级元素也会排在一行上面,不需要使用float属性
display: inline-block;
text-align: left;
}
.flex-center {
display: flex;
justify-content: center;
}
垂直方向上堆叠在一起,最好是改变宽度,使其展现出堆叠的效果。
Html:
<main>
<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>
CSS:
main {
background: white;
margin: 20px 0;
padding: 10px;
}
main div {
background: black;
margin: 0 auto;
color: white;
padding: 15px;
margin: 5px auto;
}
main div:nth-child(1) {
width: 200px;
}
main div:nth-child(2) {
width: 400px;
}
main div:nth-child(3) {
width: 125px;
}
未完待续