元素水平垂直对齐方式
行内元素水平对齐方式:text-align
| value | description |
| left | 左对齐(默认) |
| right | 右对齐 |
| center | 居中 |
| justify | 两端对齐 |
| inherit | 继承父元素的text-align |
行内元素垂直对齐方式:设置行高=高度;vertical-align
| value | description |
| baseline | 基线对齐(默认) |
| top | 元素顶端与行中最高元素顶端对齐 |
| middle | 父元素中部对齐 |
| bottom | 元素顶端与行中最低元素顶端对齐 |
块级元素水平居中对齐方式:
1.父元素设置text-align:center,子元素设置display:inline-block
<style>
.div1{
width: 200px;
height: 200px;
background-color: blue;
text-align: center;
}
.div2{
width: 100px;
height: 100px;
background-color: red;
}
.align{
display: inline-block;
}
</style>
<body>
<div class="div1">
<div class="div2 align">
</div>
</div>
</body> 2.设置margin: 0 auto
<style>
.div1{
width: 200px;
height: 200px;
background-color: blue;
}
.div2{
width: 100px;
height: 100px;
background-color: red;
}
.align{
margin: 0 auto;
}
</style>
<body>
<div class="div1">
<div class="div2 align">
</div>
</div>
</body> 3.设置flex布局,父级元素设置display:flex;justify-conter:center
<style>
.div1{
width: 200px;
height: 200px;
background-color: blue;
display: flex;
justify-content: center;
}
.div2{
width: 100px;
height: 100px;
background-color: red;
}
</style>
<body>
<div class="div1">
<div class="div2 align">
</div>
</div>
</body> 4.不设置width,水平居中,将display设置为table
<style>
.div1{
width: 200px;
height: 200px;
background-color: blue;
}
.div2{
display: table;
height: 100px;
background-color: red;
}
.align{
margin: 0 auto;
}
</style>
<body>
<div class="div1">
<div class="div2 align">
jmh
</div>
</div>
</body>块级元素垂直居中方式:
1.设置display:flex;align-items:center,父元素必须要设定height
2.设置元素display为absolute/relative/fixed,margin-top=-height/2
3.同样设置display为absolute/relative/fixed,top和bottom为0,margin为auto
浙公网安备 33010602011771号