CSS居中方案

1.水平居中

1.1 行内元素或类行内元素的水平居中

在文本,链接,图像,等display为inline,  inline-block, inline-table, inline-flex的父类元素中直接使用text-align:center;即可

如下图所示:

<html>
<head>
<style type="text/css">
h1 {text-align: center}
</style>
</head>

<body>
<h1>这是标题 1</h1>
</body>
</html>

1.2 块级元素的水平居中

1)在块级元素设置了width的情况下,使margin-left, margin-right的值为auto

<html>
<head>
<style type="text/css">
h1 {width:300px;
background-color:red;
margin: 0 auto;
}
</style>
</head>

<body>
<h1>这是标题 1</h1>
</body>
</html>

2)把需要居中元素的display设置为inline-block,接着在其父级元素设置text-align为center;

<html>
<head>
<style type="text/css">
h1 {width:300px;
background-color:red;
display:inline-block;
}
div{
text-align:center;
}
</style>
</head>

<body>
<div>
<h1>这是标题 1</h1>
</div>
</body>
</html>

可以看出,h1里面的行内元素也继承了text-align:center;的属性

3)利用flex布局,具体如下:

<html>
<head>
<style type="text/css">
h1 {width:300px;
background-color:red;
display:inline-block;
}
div{
display:flex;
justify-content:center;
}
</style>
</head>

<body>
<div>
<h1>这是标题 1</h1>
</div>
</body>
</html>

2.垂直居中 

2.1单行行内或者文本元素实现居中

1)设置padding-top等于padiing-bottom

<html>
<head>
<style type="text/css">
h1 {
background-color:red;
padding-top:20px;
padding-bottom:20px;
}
</style>
</head>
<body>
<h1 class="title1">这是标题 1</h1>
</body>
</html>

2)如果知道height的情况下,使line-height等于height(这是比较常用的方式哦)

<html>
<head>
<style type="text/css">
h1 {
background-color:red;
height:80px;
line-height:80px;
}
</style>
</head>
<body>
<h1 class="title1">这是标题 1</h1>
</body>
</html>

3)单行文本在不换行的情况下,可以使用flex布局

.flex-container{
display:flex;
flex-wrap:nowrap;
align-items:center;
}

2.2 多行文本实现垂直居中

1)为文本设置display:table-cell;和vertical-align:medium;来达到效果(常用于html表格)

<html>
<head>
<style type="text/css">
table {
background-color:red;
height:80px;
}
</style>
</head>
<body>
<table>
<tbody>
<tr>
<td style="display:table-cell; vertical-align:middle">垂直居中</td>
</tr>
</tbody>
</table>
</body>
</html>

2) 在多行情况下,也可以使用flex布局

.flex-container{
display:flex;
flex-direction:column;
justify-content:center;
}



3.水平垂直居中

1)利用绝对定位+transform:translate(-50%,-50%)  (很常用的一种方式)

.parent { 
position: relative; 
}
.child {
position: absolute; 
top: 50%; 
left: 50%; 
transform: translate(-50%, -50%); 
}

2)使用 transform 有一个缺陷,就是当计算结果含有小数时(比如 0.5),会让整个元素看起来是模糊的,一种解决方案就是为父级元素设置 transform-style: preserve-3d;

.parent { 
position: relative; 
transform-style: preserve-3d;
}
.child {
position: absolute; 
top: 50%; 
left: 50%; 
transform: translate(-50%, -50%); 
}

3)flex布局

.flex-container{
display:flex;
justify-content:center;
align-item:center;
}

基本上上面的居中方案,可以解决所有的居中问题了,哈哈哈,至少现在我还没有遇到这些方案解决不了的

参考文章:CSS居中完整指南

本博客由博主原创,如需转载需说明出处!谢谢支持!

猜你喜欢

转载自blog.csdn.net/Allenyhy/article/details/81624418