css中常见居中对齐方式梳理
一,文本内容居中对齐 :text-align
作用:使父级盒子内容水平对齐,如文字,图片等元素
用法:text-align属性有常见的三个属性值:left,right,center;
<html lang="en">
<head>
<title> test</title>
<style>
body{
text-align: center;
}
</style>
</head>
<body>
文字内容水平居中
</body>
</html>
适用范围:可作用于文字,图片行内块标签,行内标签
二,块级元素的居中对齐方式:margin;
作用:使宽高一定的块级盒子位置水平居中
用法:margin: 0 auto;上下边距为零,左右外边距自适应相等。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
margin: 0 auto;
width: 300px;
height: 300px;background-color: aqua;
}
</style>
</head>
<body>
<div class="box">
</div>
</body>
</html>
三、元素间的垂直居中对齐: vertical-align
作用:解决行内元素、行内块元素垂直对齐方式,常见的属性值有:baseline/基线对齐,top/顶部对齐,middle/中部对齐,bottom/底部对齐
用法:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
img{
width: 500px;
vertical-align:middle;
}
</style>
</head>
<body>
<img src="./cf21566287050731288566abf9745ca.png" >
<span >
一段文字顶顶顶顶顶顶顶
</span>
</body>
</html>
四、通过定位position,实现居中效果
作用:可自由的改变元素位置
用法:position,水平,垂直方向各有三个值,可将盒子水平,垂直位移方向设为距父级的50%,再用transform位移属性将盒子位移自身的一半的像素。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 300px;
height: 300px;
background-color: pink;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>