如何在960px断点后将图片显示为正方形并置于段落右侧?
问题描述
需要实现:视口宽度达到960px断点后,图片在段落右侧显示为正方形;960px以下显示横向图。要求仅修改<img>标签,通过添加srcset和sizes属性完成,需准备1张大尺寸正方形图片,以及4张适配960px断点前的横向最优尺寸图片。
尝试的HTML代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Picture This!</title> <link rel="stylesheet" href="style.css"> </head> <body> <header class="header"> <div class="title"> <h1>Picture This!</h1> <h4>My Really Cool Blog Post</h4> </div> <img src="images/museum_landscape_320px.jpg" alt="Picture of historical museum" srcset="images/museum_landscape_320px.jpg 320w, images/museum_landscape_480px.jpg 480w, images/museum_landscape_720px.jpg 720w, images/museum_square_800px.jpg 800w, images/museum_landscape_960px.jpg 960w" sizes="(min-width: 960px) 800px, 50vw"> </header> </body> </html>
解决方案
你目前的代码问题出在srcset的资源逻辑和sizes的断点规则不匹配,导致浏览器无法正确在960px后选择正方形图并按正方形尺寸渲染。以下是修正后的<img>标签代码:
<img src="images/museum_landscape_320px.jpg" alt="Picture of historical museum" srcset="images/museum_landscape_320px.jpg 320w, images/museum_landscape_480px.jpg 480w, images/museum_landscape_720px.jpg 720w, images/museum_landscape_960px.jpg 960w, images/museum_square_800px.jpg 800w" sizes="(min-width: 960px) 300px, 100vw">
核心修改说明
- srcset顺序优化:将横向图按分辨率从小到大排列,正方形高分辨率图放在最后,浏览器会根据当前视口和
sizes规则自动匹配最适合的资源; - sizes规则修正:
(min-width: 960px) 300px:当屏幕宽度≥960px时,图片显示宽度固定为300px,由于正方形图本身是1:1比例,浏览器会自动渲染成300x300的正方形;100vw:当屏幕宽度<960px时,图片占满整个视口宽度,适配横向图的显示布局。
如果想要大屏下的正方形随视口等比例缩放,可将sizes修改为(min-width: 960px) 33vw, 100vw,这样正方形会保持1:1比例的同时,占视口宽度的三分之一,适配不同尺寸的大屏设备。
内容的提问来源于stack exchange,提问作者Enhance
相关产品推荐
相关产品推荐

