【问题标题】:How to target a "style" element that was applied on a div through the html [duplicate]如何定位通过 html 应用于 div 的“样式”元素 [重复]
【发布时间】:2025-12-25 17:05:11
【问题描述】:
<div style="margin: 4rem 0  4rem 0;">
<h1>Some Content</h1>
</div>

我正在尝试编写一个媒体查询来忽略此规则.. style="margin: 4rem 0 4rem 0;"在某个视口。除了给 div 一个 class 或 id 并在媒体查询中定位 class 或 id 之外,还有没有办法只定位这个特定的 div 而忽略样式规则?我知道只添加一个类没什么大不了的,但我只是好奇你是否可以在不添加类或 id 的情况下做到这一点。

【问题讨论】:

  • 请阅读 CSS 特异性。除非使用!important,否则使用style="" 属性覆盖直接内联定义的这些规则是不切实际的(也不应该这样做)。您需要在其他地方定义这些默认规则,即在&lt;style&gt; 标记中或&lt;link&gt; 外部引用

标签: html css media-queries


【解决方案1】:

我认为你不能重写页边距样式。为此,您应该创建一个类,然后它就会起作用。

<div class="div">
    <h1>Some Content</h1>
</div>

<style>
    div {
        margin: 4rem 0 4rem 0;
    }
    
    @media screen and (max-width: 1000px) {
        .div {
            margin: 0 0 0 0;
            color: red;
        }
    }
</style>

【讨论】:

    【解决方案2】:

    您可以将媒体查询应用于 div。根据您的 html dom 的结构,您可以使用 css 定位孩子和兄弟姐妹。缩小浏览器窗口的宽度,您应该会看到 div 的背景变为浅蓝色。是的,您甚至可以更改边距,但您需要使用 !important。

    @media only screen and (max-width: 600px) {
      div {
        background-color: lightblue;
        margin:0!important;
      }
    }
    <div style="margin: 4rem 0  4rem 0;">
    <h1>Some Content</h1>
    </div>

     body div:first-child
       {
          color:red;
       }
    <html>
     <head>
      
     </head>
     <body>
      <div>I should be red.</div>
      <div>This is not red.</div>
     </body>
    </html>

    【讨论】:

    • 不会应用边距:0 !important;应用于 html 中的所有 div 元素,而不是将其应用于特定的 div?
    • 是的。但这只是一个示例,展示了 !important 的用法。这就是为什么我说这取决于你的 html 的结构。请参阅我更新的 sn-p 中的第二个示例
    【解决方案3】:

    如果你不能添加class或id来指定选择器,你仍然可以通过属性使用选择器。

    在你的情况下,它看起来像这样:

    @media screen and (max-width: 1000px) {
      div[style="margin: 4rem 0  4rem 0;"] {
        ...
      }
    }
    

    【讨论】:

      最近更新 更多