【问题标题】:Title and mouse hover标题和鼠标悬停
【发布时间】:2017-03-03 23:00:50
【问题描述】:

我是 css 初学者,但遇到了一个小问题。我已经创建了带有标题的标题。标题名称由两部分组成。第一部分只是文本,但第二部分是带背景的文本。我想创建一个标题,它会改变 :hover 上的文本颜色和背景。但是,如果您从右侧将鼠标悬停在标题上,一切正常,但从左侧没有。

这是我的代码

#rus {
  background: red none repeat scroll 0 0;
  border-radius: 8px;
  color: white;
  padding: 4px 5px;
}

#rus:hover {
  background: white;
  border-radius: 8px;
  color: red;
  padding: 4px 5px;
  border: 1px solid red;
}

h1 {
  border: 0;
  font-family: inherit;
  font-size: 100%;
  font-style: inherit;
  font-weight: inherit;
  margin: 0;
  outline: 0;
  padding: 0;
  vertical-align: baseline;
  clear: both;
}

#site-title {
  margin-right: 270px;
  padding: 3em 0 0;
  font-family: 'Ubuntu', sans-serif;
}

#site-title a {
  color: #111;
  font-size: 30px;
  font-weight: bold;
  line-height: 36px;
  text-decoration: none;
}

#site-title a:hover,
#site-title a:focus,
#site-title a:active {
  color: #1982d1;
}
<hgroup>
  <h1 id="site-title">
    <a href="#" rel="home">Bundesliga 
      <span id="rus">RUS</span>
    </a>
  </h1>
</hgroup>

如您所见,span 标签放置在链接标签中。如果我从右侧悬停它会影响链接标签和跨度,因为无论如何鼠标都在链接标签上。但从右侧鼠标悬停只触及链接标签,跨度不受影响。 我应该更改什么以使整个标题在鼠标悬停时更改其 CSS 属性?

【问题讨论】:

  • 你说的“标题”到底指的是什么?
  • 请包含所有相关代码。您缺少与您引用的标题相关的开始标签和 CSS。
  • 对不起大家这是我第一次在这里发帖。
  • 感谢额外的代码。您可以编辑您的问题以将其包含在其中吗?

标签: html css


【解决方案1】:

您需要做的就是将:hover 从您的跨度移动到父级a

#rus {
    background: red;
    border-radius: 8px;
    color: white;
    padding: 4px 5px;
}

a:hover #rus {
    background: white;
    border-radius: 8px;
    color: red;
    padding: 4px 5px;
    border: 1px solid red;
}

h1 {
    border: 0;
    font-family: inherit;
    font-size: 100%;
    font-style: inherit;
    font-weight: inherit;
    margin: 0;
    outline: 0;
    padding: 0;
    vertical-align: baseline;
    clear: both;
}

#site-title {
    margin-right: 270px;
    padding: 3em 0 0;
    font-family: 'Ubuntu', sans-serif;
}

#site-title a {
    color: #111;
    font-size: 30px;
    font-weight: bold;
    line-height: 36px;
    text-decoration: none;
}

#site-title a:hover,
#site-title a:focus,
#site-title a:active {
    color: #1982d1;
}
<hgroup>
  <h1 id="site-title">
    <a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">Bundesliga 
      <span id="rus">RUS</span>
    </a>
  </h1>
</hgroup>

【讨论】:

  • 为了更好地理解我的麻烦,看看这个jsfiddle.net/8886oab6/5 如果你从右侧悬停鼠标,它会改变文本和背景的颜色。但从左侧它改变了只有“德甲”字样的颜色。 “RUS”和红色背景不受影响。这个想法是在鼠标悬停时更改整个文本的颜色和背景颜色。
  • 是的。您需要将#rus:hover 替换为a:hover #rus,这是您的updated fiddle
  • 更新了答案以匹配您的代码,并使用您的代码示例更新了您的问题。编码愉快!
  • 感谢您的宝贵时间!只是一个理论问题。 a:hover 会影响所有的选择器/id/类吗?例如,如果我将 #b1 .tube 放在 a:hover 之后,它们也会更改颜色或属性值?
  • CSS 选择器将括号中的规则应用于任何匹配的元素,如果它是为规则指定的最强(最具体)选择器。所以,是的:a:hover 将适用于任何悬停的&lt;a&gt; 元素,除非更强的选择器为悬停的元素另行指定。要确定在某个特定时刻适用的内容,您可以在任何主要浏览器中使用元素检查器,它还允许您指定元素的状态,包括悬停。它将向您显示适用的规则以及它们的定义位置。显示已定义但未应用的规则,通常为描边或灰显。
猜你喜欢
  • 1970-01-01
  • 2011-05-26
  • 2017-10-14
  • 2011-07-07
  • 1970-01-01
  • 2011-08-04
  • 2018-09-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多