【前端芝士树】如何对元素块实现居中(垂直和水平方向都居中)?

本文介绍了前端开发中常见的元素垂直及水平居中方法,包括使用Flex布局、绝对定位、Fixed定位以及display:table-cell等技术手段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【前端芝士树】如何对元素块实现垂直居中?

clipboard.png

水平居中和垂直居中是前端开发过程中肯定会遇到的问题,下面我讲解几种常见的方式。

1/ 利用Flex布局来实现极速居中

The HTML

<div class="container">
    <!--// Any content in here will be centered.-->
    <img src="fireworks.jpg" alt="fireworks">
</div>

The CSS

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

2/ 绝对定位下,已知目标元素宽高,利用CSS或者JS实现固定长宽容器的居中

The HTML

.item{
    margin:0 auto;
    width:200px;
    height:200px;
}

2.1 margin 设为宽度的一半或者auto

.item{
    width:300px;
    height:200px;
    
    position:absolute;
    left:50%;
    top:50%;
    margin:-100px 0 0 -150px;
    //或者 margin: auto;
}

2.2 使用jquery计算 left 和 top 的值

$(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

.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

 .container {
    width: 400px;
    display: table-cell;
    vertical-align: middle;
}

.item {
    margin: 0 auto;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值