【前端芝士树】如何对元素块实现居中(垂直和水平方向都居中)?
【前端芝士树】如何对元素块实现垂直居中?水平居中和垂直居中是前端开发过程中肯定会遇到的问题,下面我讲解几种常见的方式。
1/ 利用Flex布局来实现极速居中The HTML
代码语言:javascript代码运行次数:0运行复制

代码语言:javascript代码运行次数:0运行复制.container{
display: flex;
justify-content: center;
align-items: center;
}2/ 绝对定位下,已知目标元素宽高,利用CSS或者JS实现固定长宽容器的居中The HTML
代码语言:javascript代码运行次数:0运行复制.item{
margin:0 auto;
width:200px;
height:200px;
}2.1 margin 设为宽度的一半或者auto代码语言:javascript代码运行次数:0运行复制.item{
width:300px;
height:200px;
position:absolute;
left:50%;
top:50%;
margin:-100px 0 0 -150px;
//或者 margin: auto;
}2.2 使用jquery计算 left 和 top 的值代码语言:javascript代码运行次数:0运行复制$(window).resize(function(){
$('.item').css({
position:'absolute',
left: ($(window).width() - $('.item').outerWidth())/2,
top: ($(window).height() - $('.item').outerHeight())/2
});
});
// To initially run the function:
$(window).resize();3/ Fixed定位下,利用margin:auto实现fixed元素的居中The CSS
代码语言:javascript代码运行次数:0运行复制.item{
position: fixed;
margin: auto;
top: 0;
right: 0;
left: 0;
bottom: 0;
width: 200px;
height: 100px;
}4/ 利用display: table-cell来实现居中注意,父元素的宽度需要被定义,同时父元素的vertical-align以及item的margin: auto都是缺一不可的
The CSS
代码语言:javascript代码运行次数:0运行复制 .container {
width: 400px;
display: table-cell;
vertical-align: middle;
}
.item {
margin: 0 auto;
}
Copyright © 2022 流光追月·网游特刊 All Rights Reserved.