我有以下代码,这些代码是从教程中获得的。当我在Chrome或Firefox上运行时,无论我是否调整窗口大小,这两行都会显示出来。我做错了什么?
<html>
<head>
<style>
#content-desktop {display: block;}
#content-mobile {display: none;}
@media screen and (max-width: 768px) {
#content-desktop {display: none;}
#content-mobile {display: block;}
</style>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<div class="content-desktop">
This is the content that will display on DESKTOPS.
</div>
<div class="content-mobile">
This is the content that will display on MOBILE DEVICES.
</div>
<body>
</body>
</html>
首先,您使用的是class="content-desktop"
和class="content-mobile"
,而CSS需要id
,因为您使用了#content-desktop
和#content-mobile
。
其次,你忘了合上支架。
在CSS中,您需要使用点.
来选择class
,使用#
来选择id
。
试试这个:
.content-desktop {display: block;}
.content-mobile {display: none;}
@media screen and (max-width: 768px) {
.content-desktop {display: none;}
.content-mobile {display: block;}
}
您永远不会关闭此处打开的括号:
@media screen and (max-width: 768px) {
因此,整个@media
规则被解析器丢弃。只需在应该关闭的地方关闭它(可能在</style>
之前(。
您从未关闭括号,您正在使用#来定位需要使用的类。你的div也在body标签之外。此外,在这种情况下,您还需要查询上述缩放比例。测试了以下代码。你可以直接运行它。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.desktop {
background-color: yellow;
padding: 20px;
}
@media screen and (max-width: 600px) {
.desktop {
display: none;
}
.mobile{
background-color: red;
padding: 20px;
}
}
@media screen and (min-width: 600px){
.mobile{
display: none;
}
}
</style>
</head>
<body>
<h2>Hide elements on different screen sizes</h2>
<div class="desktop">Show on desktop but hide on mobile.</div>
<div class="mobile">Show on Mobile but hide on desktop</div>
</body>
</html>