[原]在工作中使用到的CSS居中内容的方法

水平居中

水平居中的方法大家都知道其实很简单

如果是对块级元素

html

1
<div class="content"></div>

css

1
2
3
4
5
.content {
width: 100px;
height: 100px;
margin: 0 auto;
}

如果是对文本居中直接使用:text-algin: center;

上下居中

方法 1:

对于单行文本使用 line-height:height(这个 height 就是外层 div 的高度)

html

1
<div class="content"><p>我是一段测试文本</p></div>

css

1
2
3
4
5
6
7
.content {
width: 100px;
height: 100px;
}
.content p {
line-height: 100px;
}

这里上下左右居中的方法是:

css

1
2
3
4
.content p {
line-height: 100px;
text-algin: center;
}

方法 2:

flex 布局方法上下居中,justify-content 控制水平居中,align-items 控制上下居中

html

1
<div class="content"><p>我是一段测试文本</p></div>

css

1
2
3
4
5
6
7
8
.content {
width: 100px;
height: 100px;
display: flex;
justify-content: center;
align-items: center;
background: red;
}

方法 3:

position:absolute 居中定位方法,此方法是设置 top:50%,然后设置 margin-top:-height/2,height 为目标元素的高度,所有此方法在目标元素有特定高度的时候有用

假设我的 body 内容高度为 1000px

html

1
2
3
<body>
<div class="content"><p>adadadada</p></div>
</body>

css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
body {
position: relative;
height: 1000px;
}
.content {
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
background: red;
}

方法 4:

display 有一个模拟表格的值 table

假设我们的 body 高度为 1000px,这个使用我们会发现 .content 的高度 height=100 是没有用的,他的高度等于 display:table 所在的高度,这里为 body 也就是 1000px
但是他里面的内容上下居中,所以我们在使用的时候一定要注意:在使用此方法时高度可伸缩内容上下居中

html

1
2
3
<body>
<div class="content"><p>adadadada</p></div>
</body>

css

1
2
3
4
5
6
7
8
9
10
11
12
body {
display: table;
height: 1000px;
}
.content {
width: 100px;
height: 100px;
display: table-cell;
background: red;
vertical-align: middle;
text-align: center;
}

方法 5:

vm vh
只要设置 margin 的上下间距,使之 heigit + margin-top +margin-bottom = 100 ,width + margin-left + margin-right = 100 ,就能够响应垂直居中

html

1
2
3
<body>
<div class="content"><p>adadadada</p></div>
</body>

css

1
2
3
4
5
6
7
8
9
body {
display: table;
height: 1000px;
}
.content {
width: 50vw;
height: 50vh;
margin: 25vh auto;
}

在互联网上还有其他使用的方法请大家自行查找,并且还有许多 js 的方法,通过 JS 进行上下居中的基本思想是对目标元素定位,然后设置他的 css 属性,这样就能进行动态的改变不会受到 CSS 的局限性,根据不同的使用场景选择合适的处理方式!

如果对您有所帮助或者对博主有更多的话说,欢迎你去我的 GitHub 留下一个您的 start 和 issues

前往 LEE 的 github 给他一个 Start 鼓励一下吧

原创转载请标注出处:https://leehongqiang.github.io