1.负边距居中
示例代码:
<head>
<meta charset="UTF-8">
<title>元素居中</title>
<style>
.father{
background-color: navy;
width: 400px;
height: 300px;
position: absolute;
}
.son{
background-color: #cccccc;
width: 100px;
height: 100px;
position: absolute;
top:50%;
margin-top: -50px;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
效果如下:
说明: 负边距指的是子元素的margin-top
设置为自身的一半,当为0时子元素上边界在父元素的中线上,所以设置负值;父元素的position
属性设置为‘relative’或者‘absolute’,子元素设置为‘absolute’,能够相对于父元素绝对定位。本例仅实现垂直居中,可以类比实现水平居中。(优点:写法比较流行,推荐使用。缺点:需要知道子元素本身的尺寸)
2. 边距为0自动居中
示例代码:
<head>
<meta charset="UTF-8">
<title>元素居中</title>
<style>
.father{
background-color: navy;
width: 400px;
height: 300px;
text-align: center;
position: absolute;
}
.son{
background-color: #cccccc;
width: 100px;
height: 100px;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
效果如下:
说明: ①子元素相对于父元素绝对定位;②父元素一定要设置position
属性为‘relative’或者‘absolute’;③子元素四个方向属性设置为0。(优点:写法简洁,不需要知道子元素的尺寸)
3. 设置display
示例代码
<head>
<meta charset="UTF-8">
<title>元素居中</title>
<style>
.father{
background-color: navy;
width: 400px;
height: 300px;
text-align: center;
}
.son{
background-color: #cccccc;
width: 100px;
height: 100px;
display: inline-block;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
效果如下:
说明: 在子元素中设置display
属性为inline-block后,能相对于父元素表现内联样式,所以父元素的text-align: center;
文本居中对子元素生效(缺点:只能实现水平居中)
补充:
水平居中
对于行内元素: text-align: center;
对于确定宽度的块级元素:
- width和margin实现。margin: 0 auto;
- 绝对定位和margin-left: -width/2, 前提是父元素position: relative
对于宽度未知的块级元素
- table标签配合margin左右auto实现水平居中。使用table标签(或直接将块级元素设值为display:table),再通过给该标签添加左右margin为auto。
- inline-block实现水平居中方法。display:inline-block;(或display:inline)和text-align:center;实现水平居中。
- 绝对定位+transform,translateX可以移动本身元素的50%。
- flex布局使用justify-content:center
垂直居中
-
利用line-height实现居中,这种方法适合纯文字类
-
通过设置父容器相对定位,子级设置绝对定位,标签通过margin实现自适应居中
-
弹性布局flex:父级设置display: flex; 子级设置margin为auto实现自适应居中
-
父级设置相对定位,子级设置绝对定位,并且通过位移transform实现
-
table布局,父级通过转换成表格形式,然后子级设置vertical-align实现。(需要注意的是:vertical-align: middle使用的前提条件是内联元素以及display值为table-cell的元素)。