CSS实现元素居中样式(水平居中和垂直居中)

2020-03-29 135 0

水平居中

1.text-align:center;
此用法需要满足:父元素为块级元素(block)
可以实现块级元素内样式居中,子元素可以为:inline-block,inline,inline-flex

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.main {
text-align: center;
background-color: green;
}
.box1 {
display: inline-flex;
width: 60px;
height: 60px;
border: 1px solid #ccc;
}
.box2 {
display: inline-block;
width: 60px;
height: 60px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div class="main">
<div class="box1"></div>
<div class="box2"></div>
</div>
</body>
</html>

2.margin:0 auto;
设置要求:块级元素(block)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.main {

background-color: green;
}
.box1 {
width: 60px;
height: 60px;
border: 1px solid #ccc;
margin: 0 auto;
}
.box2 {
display: inline-block;
width: 60px;
height: 60px;
border: 1px solid #ccc;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="main">
<div class="box1"></div>
<div class="box2"></div>
</div>
</body>
</html>

3.利用弹性布局实现居中
通过弹性布局设置主轴的对齐方式(justify-content: center;)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.main {
display: flex;
color: #fff;
background-color: green;
justify-content: center;
}
.box1 {
width: 60px;
height: 60px;
border: 1px solid #ccc;
}
.box2 {
width: 60px;
height: 60px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div class="main">
<div class="box1">box1</div>
<div class="box2">box2</div>
</div>
</body>
</html>

垂直居中

1.容器height与line-height高度一致
对于内容的居中实现较为简单,但不能对于整个元素标签进行居中

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.main {
height: 180px;
color: #fff;
background-color: green;
line-height: 180px;
}
.box1 {
width: 60px;
height: 60px;
border: 1px solid #ccc;

}
</style>
</head>
<body>
<div class="main">
<div class="box1">文本内容垂直居中</div>
</div>
</body>
</html>

2.利用flex布局实现
原理同利用flex实现水平居中相同,只需更改主轴方向即可

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.main {
height:400px;
display: flex;
color: #fff;
background-color: green;
flex-direction: column;/*更改主轴方向为垂直方向*/
justify-content: center;
}
.box1 {
width: 90px;
height: 90px;
border: 1px solid #ccc;

}
</style>
</head>
<body>
<div class="main">
<div class="box1">box1</div>
</div>
</body>
</html>

扫描加入网页设计QQ群、建站如此简单

本文地址:https://www.usuuu.com/a/fW4eu3hv