引言

我们在做官网类项目的时候,设计稿通常是使用按照1920*1080(16:9)的分辨率来设计的,但是电脑端的浏览器窗口宽度是不固定的,用户可能会根据使用场景随意拖动浏览器窗口宽高比,就会导致本来应该好好的布局出现遮挡、错位等情况,特别的

作为一名强迫症前端,绝对不允许这么丑的页面在我的coding下出现!!

1K(1920 * 1080)、2K(2560 * 1440)、4K(3840 * 2160)、带鱼屏(3440 * 1440)的屏幕,宽高比分别是16:9、16:9、16:9、21:9,首先考虑21:9的带鱼屏,如果保持比例缩放,底部会被遮挡不保持比例缩放又会使上下元素挤在一起,非常棘手! 再或者用户改变浏览器窗口整出来一个1:1的窗口,不就炸了嘛。

实现思路

找到一个和我想象适配方案的几乎一模一样的网站,绝区零 官网,

  1. 设置一个21:9的容器,上下左右居中

  2. 在容器中再添加一个16:9容器,在父级容器中左右居中

  3. 在16:9的容器中进行开发内容

动图展示

参考代码

<body>
    <div class="box">
        <div class="container"></div>
    </div>
</body>

html,
body {
    margin: 0;
    padding: 0;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f5f5f5;
}

.box {
    width: auto;
    height: auto;
    max-width: 100vw;
    max-height: 100vh;
    aspect-ratio: 21 / 9;
    background-color: #e0e0e0;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

@media (max-aspect-ratio: 21/9) {
    .box {
        width: 100vw;
        height: calc(100vw * 9 / 21);
    }
}
@media (min-aspect-ratio: 21/9) {
    .box {
        height: 100vh;
        width: calc(100vh * 21 / 9);
    }
}

.container {
    margin: 0 auto;
    width: auto;
    height: auto;
    max-width: 100%;
    max-height: 100%;
    aspect-ratio: 16 / 9;
    background-color: #ffffff;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

演示:借绝区零官网效果展示(侵权删):

致命兼容性问题

使用 aspect-ratio 来使.box.container能够固定尺寸缩放并不是一个完美的解决方案,它有一个致命问题就是兼容性很差IE浏览器全面覆灭!!

解决兼容性问题