添加的button2元素Media Queries不生效,求解决方案
问题
我自定义了一个button2元素,但媒体查询对它完全不生效——其他元素的媒体查询都正常,只有这个元素出问题。我试过移除only、screen这类关键字,还是没用。我想要在移动端让这个元素宽度设为100%,相关代码如下:
const showImageButton = document.getElementById("show-image-button"); const myImage = document.getElementById("my-image"); showImageButton.addEventListener("click", () => { myImage.hidden = !myImage.hidden; });
button2, input[type=submit] { cursor: pointer; } button2, input, textarea { -webkit-appearance: none; -moz-appearance: none; } button2 { color: currentColor; overflow: visible; margin: 0 } button2 { border-style: outset; line-height: 1.6; margin: 0 0 0px; text-align: center; line-height: 60px; max-width: 300px; border-radius: 10px; display: inline-block; text-align: center; text-decoration: none; position: relative; font-weight: 300; font-size: .85em; width: 100%; } So i want to make it to be width 100% on mobile @media only screen { .button2 { width: 100%; } }
<button2 id="show-image-button">尺码表</button2> <img id="my-image" src="https://cdn.shopify.com/s/files/1/2999/5106/files/True-to-Sole-nike-sneaker-sizechart_760x760.jpg?v=1611582903" hidden>
解决方案
问题出在三个关键点:
- 媒体查询语法错误:你的媒体查询既没指定断点(比如移动端常用的
max-width),还把注释文本和代码混写在一起,导致规则完全不生效。 - 选择器不匹配:CSS里用了
.button2(类选择器),但HTML里是自定义元素<button2>,应该用元素选择器button2,不能加前面的点。 - 宽度限制冲突:原样式里给
button2设置了max-width: 300px,就算把width设为100%,实际宽度还是会被限制在300px以内,移动端需要把这个限制也去掉。
修正后的CSS代码如下:
button2, input[type=submit] { cursor: pointer; } button2, input, textarea { -webkit-appearance: none; -moz-appearance: none; } button2 { color: currentColor; overflow: visible; margin: 0 } button2 { border-style: outset; line-height: 1.6; margin: 0 0 0px; text-align: center; line-height: 60px; max-width: 300px; border-radius: 10px; display: inline-block; text-align: center; text-decoration: none; position: relative; font-weight: 300; font-size: .85em; width: 100%; } /* 移动端媒体查询,以768px为断点,可按需调整 */ @media only screen and (max-width: 768px) { button2 { width: 100%; max-width: 100%; /* 移除最大宽度限制 */ } }
内容的提问来源于stack exchange,提问作者Vendel 3131
相关产品推荐
相关产品推荐

