1.text-align:center (单行多行都可以)
在父容器里水平居中 inline 文字,或 inline 元素
2.垂直居中 inline 文字,inline 元素(单行多行都可以)
单用 vertical-align:middle;没有用,要搭配父元素display: table;子元素display: table-cell; vertical-align:middle;
3.单行文字或 inline 元素垂直居中 height=line-height;
4.块级元素水平居中margin:auto;
用此方法水平垂直居中
子元素{width: 50%; 百分比或者像素都可以
height: 50%;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;//必须要写}
建议加 overflow: auto,防止内容溢出
( 块级还可以自己计算,改变margin或者padding)
5. transform:translate(-50%,-50%); 不知道宽高用这种方法-50%自己的宽度和高度一半,块级,百分比计算不是以父元素为基准,而是以自己为基准
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0;
padding: 0;
}
#container{
width: 600px;
height: 400px;
background-color: darkgray;
position: relative;
}
#sub-div{
background-color: pink;
transform: translate(-50%,-50%);
left:50%;
top:50%;
position: absolute;
}
</style>
</head>
<body>
<div id="container">
<div id="sub-div">
啊啊啊啊啊
</div>
</div>
</body>
</html>
6.块级元素水平垂直居中,
在父元素中,设置子元素
width:400px;
height:400px;
position:absolution;
margin-top:-高度的一半;
margin-left:-宽度的一半;
7. 图片居中
(1)全都撑开
width: auto;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
(2)水平居中
将图片以块级元素方式显示,display:block; margin:0 auto;
height=line-height,不是正中?
(3)直接计算,设置margin或者padding
(4)dispaly:table display:table-cell; 我自己写的没有成功
<div id="container">
<img src="img/ab3.jpg" alt="">
</div>
别人的可以
<div style="text-align: center; width: 500px;height:500px; display: table;border: green solid 1px;">
<span style="display: table-cell; vertical-align: middle; "><img alt="" src="img/ab3.jpg" style="display: inline-block;" /></span>
</div>