为什么针对不同iPad竖屏编写的媒体查询会出现互相覆盖的冲突?
冲突原因
你当前使用的媒体查询宽度范围存在重叠:12.9英寸iPad Pro竖屏逻辑宽度为1024px,同时落在了你写的iPad Pro(1024px~1366px)和iPad 10(810px~1080px)两条规则的覆盖范围内。CSS中优先级相同的规则,写在后面的会覆盖前面的,所以你给iPad 10设置的红色背景会覆盖iPad Pro的蓝色背景。
解决方案
有两种方式可以实现精准适配,按需选择即可:
方案1:使用精确设备参数匹配(最精准,不会出现范围重叠)
直接匹配各型号iPad的固定逻辑分辨率和像素比,完全避免范围重叠问题:
/* 确保页面head已添加viewport标签:<meta name="viewport" content="width=device-width, initial-scale=1.0"> */ /* iPad Air 2 竖屏 */ @media only screen and (device-width: 768px) and (device-height: 1024px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) { /* 自定义样式 */ } /* iPad 10 竖屏 */ @media only screen and (device-width: 820px) and (device-height: 1180px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) { body { background-color: red; } } /* 12.9英寸 iPad Pro 竖屏 */ @media only screen and (device-width: 1024px) and (device-height: 1366px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) { body { background-color: blue; } }
方案2:调整规则排列顺序(无需修改原有查询规则)
如果你不想改动已经写好的媒体查询范围,只需要把覆盖范围更大、优先级更高的规则写在后面即可。比如你现在的场景,把iPad Pro的媒体查询整体挪到iPad 10的媒体查询之后,重叠范围的样式就会优先应用iPad Pro的规则。
内容的提问来源于stack exchange,提问作者Paula
相关产品推荐
相关产品推荐

