CSS代码中media query不生效,无法实现响应式字号调整,求排查
问题排查结果
核心问题:CSS声明顺序错误导致媒体查询样式被覆盖
选择器权重相同时,后声明的CSS样式会覆盖先声明的样式。你的代码顺序存在问题:
- 先写了
@media媒体查询里的.mainco h1 { font-size:20px; } - 后面又写了全局的
.mainco h1 { font-size: 60px; }
二者选择器权重完全一致,所以不管屏幕宽度是否小于800px,后面声明的60px都会覆盖媒体查询的20px,自然看不到适配效果。
其他附带问题
- 没有给
h1内嵌的span、h2元素写小屏适配的字体规则,就算h1样式生效,这两个元素还是会维持大尺寸 .buttons设置了min-width:400px,宽度小于400px的设备打开时会出现横向滚动条
修复方案
将媒体查询代码移动到所有普通样式的末尾,同时补充其他需要适配的元素样式即可,参考修改后的完整CSS:
/*this is a universal selector to clear the padding and margin*/ *{ padding: 0; margin: 0; box-sizing: border-box; } body{ font-family:Verdana, Geneva, Tahoma, sans-serif; } /*------------------------------------- main --------------------------------------*/ /*here is the style of the main as a section*/ main{ background: url(code1.jpg) purple; background-repeat: no-repeat; background-size:cover ; width: 100%; height: 630px; color: white; font-family: "alternate gothic"; padding: 20px 0 0 0; } /*the style of the main section's text block*/ .mainco{ width: 40%; max-height: 70%; text-align: center; margin: 10% 30px; display: flex; flex-direction: column; justify-content: center; align-items: center; } /*the style of the h1 of the text*/ .mainco h1 { font-size: 60px; } .mainco h1 span{ text-shadow: 3px 3px rgb(167, 119, 119); font-size: 75px; } /*the style of h2 of the text*/ main h2{ font-size: 50px; } .buttons{ min-width: 400px; } /*the style of the two button's text containers*/ .buttons p{ padding: 20px; background-color: brown; display: inline-block; margin: 60px 20px; } /*styling the button's text*/ .buttons a{ text-decoration: none; color: white; display: block; width: 100%; height: 100%; } /* 媒体查询移到所有普通样式末尾,补充其他元素适配规则 */ @media only screen and (max-width: 800px){ .mainco h1{ font-size:20px; } .mainco h1 span{ font-size: 30px; } main h2{ font-size: 18px; } .buttons{ min-width: unset; width: 100%; display: flex; flex-direction: column; } .buttons p{ margin: 10px 20px; } }
内容的提问来源于stack exchange,提问作者0416
相关产品推荐
相关产品推荐

