css的各种居中方法
css的居中主要分为水平居中和垂直居中。
水平居中
水平居中可分为行内元素水平居中和块级元素水平居中。
1. 行内元素水平居中
这里行内元素是指文本text、图像img、按钮超链接等,只需给父元素设置text-align:center
即可实现。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.wrap{
width: 200px;
height: 100px;
border: 1px solid #000;
text-align: center;
color: red;
}
</style>
</head>
<body>
<div class="wrap">
<span>行内元素水平居中</span>
</div>
</body>
</html>
如图所示:
3. 块级元素水平居中
1)定宽块级元素水平居中
只需给需要居中的块级元素加margin:0 auto
即可,但这里块状元素的宽度width值一定要设置
2)不定宽块级元素水平居中
方法一、设置dispaly:table
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.center {
display: table;
margin: 0 auto;
border: 1px solid red;
}
</style>
</head>
<body>
<!-- 设置dispaly:table -->
<div class="center">水平居中</div>
</body>
</html>
如图:
方法二、设置inline-block
(多个块状元素)
子元素设置inline-block,同时父元素设置text-align:center
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.center1 {
width:200px;
height:200px;
text-align: center;
border:1px solid #000;
}
.inlineblock-div {
display: inline-block;
}
</style>
</head>
<body>
<!-- 设置dispaly:inline-block -->
<div class="center1">
<div class="inlineblock-div">块级元素1</div>
<div class="inlineblock-div">块级元素2</div>
</div>
</body>
</html>
如图:
方法三、设置flex布局(较常用)
只需把要处理的块状元素的父元素设置display:flex,justify-content:center;
垂直居中
行内元素
1、单行文本垂直居中
设置paddingtop=paddingbottom
;或设置line-height=height
;
2、多行文本垂直居中
可以将元素转为table样式,通过设置父元素table,子元素table-cell;vertical-align:middle
.center-table{
width: 200px;
height: 200px;
display: table;
}
.table-div{
display: table-cell;
vertical-align: middle;
border: 1px solid red;
}
块级元素
方法一、flex布局
在需要垂直居中的父元素上,设置display:flex;align-items:center
要求:父元素必须显示设置height值
方法二、利用position和top和负margin(需知宽高)
设置父元素为position:relative
,子元素设置为:position:absolute;top:50%;margin-top:height的一半;
.wrap{
position: relative;
width:500px;
height:500px;
border: 1px solid #000;
}
.child{
height:100px;
width:100px;
background-color: aquamarine;
color:red;
position:absolute;
top:50%;
margin-top: -50px;
}
方法三:利用position和top和transform(未知宽高)
transform中translate偏移的百分比就是相对于元素自身的尺寸而言的。
.wrap{
position: relative;
}
.child{
background-color: aquamarine;
color:red;
position:absolute;
top:50%;
transform: translateY(-50%)
}