兼容ie8的元素居中

本文介绍了一种使弹窗在不同浏览器中(包括IE8)居中的CSS和JS实现方法。通过使用固定定位和绝对定位结合transform属性,可以轻松实现现代浏览器上的居中效果。对于IE8,则通过添加额外的包裹层并利用display:table-cell属性配合JS动态设置尺寸的方法来达到兼容目的。

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

今天重新回来修改一下弹窗居中这个功能;弹窗,就是将一个框框放在屏幕中间,这个框的高度不确定。

不需要兼容ie8及以下,css用下面这个代码完全够了

.pop{
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
}
.pop-content{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    background-color: #5fa9ee;
    width: 400px;
}

有时要兼容ie8;那么就要如下:

 

方法一:

由于父元素是固定定位,采用父元素display:table-cell;vertical-align:middle;text-align:center;子元素行内快。但是在父元素固定定位或绝对定位时采用这个方法是不行的。

.popup{
    position: fixed;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    display: table-cell;
    vertical-align: center;
    text-align: center;
}
.popup-content{
    display: inline-block;
    width: 100px;
    height: 100px;
    background-color: red;
}

那么,我给父元素里面加一层,定位成相对定位怎样?然后我就发现

<div class="popup">
    <div>
        <div class="popup-content"></div>
    </div>
</div>
.popup>div{
    position: relative;
    width: 100%;
    height: 100%;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

然后我发现加的一层长宽百分比无效,又试了下px,可以。那就可以用js来设置他的长宽。(总比设置不固定宽度的popup-content好吧)

function resetPopupWrap() {
   console.log($(".popup>div"));
    <!--设置popup内容包裹层的大小-->
    $(".popup>div").width($(".popup").width());
    $(".popup>div").height($(".popup").height());
};

好了,现在就可以了,兼容所有。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值