CSS 显示:无;不适用于媒体查询中给出的条件?

问题描述 投票:0回答:1

我正在尝试定位宽度为

<= 375px
=> 376px
的设备(分别为移动设备和桌面设备)。我在 HTML 中创建了链接标签,其中不同的媒体查询链接到各自的 CSS 文件。这是我的代码:

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <link
            rel="stylesheet"
            href="mobile.css"
            media=" screen and (max-width: 375px)" />
        <link
            rel="stylesheet"
            href="desktop.css"
            media=" screen and (min-width: 376px)" />
</head>
<body>
        <div class="img-section">
            <img src="images/image-product-desktop.jpg" id="desktop" alt="" />
            <img src="images/image-product-mobile.jpg" id="mobile" alt="" />
        </div>
        <div class="parent">
            Lorem ipsum dolor sit amet consectetur adipisicing elit. Obcaecati,
            quo cupiditate similique consequuntur perferendis at asperiores
            officiis praesentium repellat aspernatur!
        </div>
</body>

desktop.css 代码:

html {
    width: 100vw;
    height: 100vh;
}

body {
    background-color: blue;
    width: 100%;
    height: 100%;
}

.img-section {
    text-align: center;
}
img#mobile {
    display: none;
}

img {
    width: 100px;
    height: auto;
}

mobile.css 代码:


html {
    width: 100vw;
    height: 100vh;
}

body {
    background-color: red;
    width: 100%;
    height: 100%;
}

.img-section {
    text-align: center;
}
img#desktop {
    display: none;
}

img {
    width: 100px;
    height: auto;
}

因此,我使用

display: none;
来根据设备确定显示哪个图像。

我注意到,当

width
恰好是
375px
时,浏览器使用 mobile.css,但会显示
img#desktop
img#mobile
两个图像,而不仅仅是
img#mobile

我尝试通过将其添加到 mobile.css 来修复它:

@media screen and (width: 375px) {
    img#desktop {
        display: none;
    }
}

但是没有成功。

我真的很想知道这是否是我犯的任何错误造成的,或者我需要补充什么。

html css media-queries screen display
1个回答
0
投票

建议您遵循移动优先设计原则。使用单个样式表,该样式表作为起点,包含您想要的移动设备的所有样式。然后,通过在必要时添加

@media (min-width: xxx)
规则,对桌面样式进行所需的任何调整,以覆盖移动样式。

body {
  background-color: red;
  height: 100svh;
}

@media (min-width: 376px) {
  body {
    background-color: blue;
  }
}

.img-section {
  text-align: center;
}

img {
    width: 100px;
    height: auto;
}

img#desktop {
  display: none;
}

@media (min-width: 376px) {
  img#desktop {
    display: initial;
  }
  img#mobile {
    display: none;
  }
}
<div class="img-section">
  <img src="https://picsum.photos/id/8/300" id="desktop" alt="" />
  <img src="https://picsum.photos/id/160/300" id="mobile" alt="" />
</div>
<div class="parent">
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Obcaecati,
  quo cupiditate similique consequuntur perferendis at asperiores
  officiis praesentium repellat aspernatur!
</div>

© www.soinside.com 2019 - 2024. All rights reserved.