如何在其他样式中控制我的 <h1> 样式

How can I control my <h1> styling in another styling?

本文关键字:样式 h1 我的 控制 其他      更新时间:2023-09-26

嘿伙计们,我希望从另一组样式规则中控制我的<h1>样式。我知道如何使用JavaScript做到这一点,但我想知道我是否可以只CSS做到这一点。为了更好地说明我的意思,请查看以下示例:

h1 {
     color: red;
     opacity: 1;
}
#menu:hover {
      /* Styling for menu bar */
      /* How can I control the style of my <h1> here? I tried:
     h1 {
        opacity: 0;
    }
    but this doesn't work... */
}

我希望这能让你了解我想做什么......这可以用CSS吗?

提前感谢您的帮助!

#menu:hover + h1 {
    opacity:0;
}

如果您的 H1 在您的菜单下。

在几种特定情况下,您可以根据一个元素的状态更改另一个元素的样式。

情况1:<h1>#menu的后裔

#menu:hover h1 {
  color:#f00;
}
<div id="menu">
  <h1>Headline</h1>
  <p>Just a paragraph to prove a point</p>
  <div>
    <h1>Another Headline that behaves exactly the same</h1>
  </div>
</div>

情况2:<h1>#menu的直系后裔

#menu:hover > h1 {
  color:#f00;
}
<div id="menu">
  <h1>Headline</h1>
  <p>Just a paragraph to prove a point</p>
  <div>
    <h1>Another Headline that is not affected</h1>
  </div>
</div>

情况3:<h1>#menu的直接继承人(兄弟姐妹)

#menu:hover + h1 {
  color: #f00;
}
<div id="menu">
  This is the div with the id 'menu', hover over it.
</div>
<h1>Headline</h1>
<p>Just a paragraph to prove a point</p>
<h1>Another Headline that is not affected</h1>

情况4:<h1>#menu的任何继承人(兄弟姐妹)

#menu:hover ~ h1 {
  color: #f00;
}
<div id="menu">
  This is the div with the id 'menu', hover over it.
</div>
<h1>Headline</h1>
<p>Just a paragraph to prove a point</p>
<h1>Another Headline that behaves exactly the same</h1>

在任何其他情况下,例如,如果<h1>#menu之前,或者它们在不同的容器中,你就不走运了,单独使用 CSS 无法做到这一点,但也许你可以使用 flexbox 对元素进行重新排序,这样<h1>是标记中#menu的继承者,但无论如何都会呈现在它上面。