不管屏幕尺寸如何变化,图片始终水平居中显示

代码如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>限制容器尺寸的水平居中方案</title>
    <style>
        /* 全屏外层容器 */
        .viewport {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 100vw;
            height: 100vh;
            background: #f5f5f5;
        }

        /* 图片容器(限制最大尺寸) */
        .image-container {
            position: relative;
            max-width: 1920px;
            max-height: 800px;
            width: 90vw;  /* 自适应宽度 */
            height: 90vh; /* 自适应高度 */
            overflow: hidden;
            border: 2px solid #333;
            background: white;
        }

        /* 固定尺寸图片 */
        .original-image {
            position: absolute;
            left: 50%;              /* 关键定位属性 */
            transform: translateX(-50%); /* 水平居中校正 */
            
            /* 保持原始尺寸(示例值需替换) */
            width: 1600px; 
            height: 1200px;
            
            /* 可选样式 */
            object-fit: contain;
            box-shadow: 0 0 15px rgba(0,0,0,0.2);
        }
    </style>
</head>
<body>
    <div>
        <div>
            <img src="https://picsum.photos/1600/1200" 
                 alt="示例图片" 
                 class="original-image">
        </div>
    </div>

    <script>
        // 自动获取图片原始尺寸(可选)
        document.querySelector('.original-image').onload = function() {
            this.style.width = this.naturalWidth + 'px';
            this.style.height = this.naturalHeight + 'px';
        };
    </script>
</body>
</html>


1、本站目前拥有近 1000+ 精品收费资源,现在加入VIP会员即可全部下载。
2、本资源部分来源其他付费资源平台或互联网收集,如有侵权请联系及时处理。
川芎模板网 » 不管屏幕尺寸如何变化,图片始终水平居中显示

发表评论

加载中~

加入本站VIP会员订阅计划,海量资源免费查看

目前为止共有 3654 位优秀的VIP会员加入! 立刻加入VIP会员