You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为<a>标签内的<h2>元素正确应用CSS:hover伪类?

Fixing the :hover Behavior for

Inside an Tag

Alright, let's break this down and get that hover behavior working consistently. First, I’ll assume your HTML structure looks something like this (since you mentioned the <h2> wraps everything except the "View" text):

<a href="#" class="coupon-link">
  <h2 class="coupon-heading">Mad Science of Colorado Coupon</h2>
  View
</a>

The wonky hover effect you’re seeing happens because you’re probably applying :hover styles directly to the <h2> instead of tying the hover state to the parent <a> tag. When you do that, the <h2> only changes color when the mouse is over it, while the "View" text only responds to the <a>’s hover—leading to that inconsistent split behavior.

Here’s the straightforward fix:

Step 1: Target the Parent 's Hover State

Instead of styling <h2>:hover, use the <a>’s hover state to control both the <h2> and the "View" text. This way, hovering anywhere inside the <a> (whether over the heading or the "View" text) triggers the same style change across all elements.

/* Default styles for the link and heading */
.coupon-link {
  color: #2d2d2d; /* Your default text color for "View" */
  text-decoration: none;
  display: inline-block; /* Ensures the <a> wraps the <h2> properly */
}

.coupon-link .coupon-heading {
  color: #4a4a4a; /* Your default color for the <h2> */
  margin: 0; /* Adjust spacing as needed */
}

/* Hover styles: Triggered when ANY part of the <a> is hovered */
.coupon-link:hover {
  color: #ffffff; /* Makes "View" white on hover */
}

.coupon-link:hover .coupon-heading {
  color: #ffffff; /* Makes the <h2> white on hover */
}

Step 2 (Optional): Add a Span for "View" for Precise Control

If you want to style "View" separately (like adding padding or a different default weight), wrap it in a <span> to target it more explicitly:

<a href="#" class="coupon-link">
  <h2 class="coupon-heading">Mad Science of Colorado Coupon</h2>
  <span class="coupon-action">View</span>
</a>

Then update your CSS to target the span directly:

.coupon-link:hover .coupon-heading,
.coupon-link:hover .coupon-action {
  color: #ffffff;
}

/* Optional: Style the "View" span differently by default */
.coupon-action {
  margin-left: 8px;
  font-weight: bold;
}

Why This Works

By attaching the :hover pseudo-class to the parent <a> tag, you’re ensuring the hover state applies to the entire clickable area. Any child elements (the <h2> and "View" text) will inherit or be targeted by the hover styles, so you get a consistent, unified hover effect no matter where the mouse lands inside the link.

内容的提问来源于stack exchange,提问作者bluedimensional

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:40:39