下面是我的HTML
<h1>Heading</h1>
<a class="button" href="#"></a>
Run Code Online (Sandbox Code Playgroud)
我想要做的是,当我悬停<a>标签时,我想<h1>纯粹使用CSS 更改标签的颜色.我怎样才能做到这一点?
PS -----*编辑*----------
如果我用一个id包裹一个div怎么办?
<div id="banner">
<h1>Heading</h1>
<a class="button" href="#"></a>
</div>
Run Code Online (Sandbox Code Playgroud)
这会有帮助吗?
Ste*_*n P 72
你可以让一个兄弟如下当该元素悬停元素的变化,例如,你可以改变你的颜色a的时候链接h1悬停,但你不能影响先前以同样的方式同胞.
h1 {
color: #4fa04f;
}
h1 + a {
color: #a04f4f;
}
h1:hover + a {
color: #4f4fd0;
}
a:hover + h1 {
background-color: #444;
}Run Code Online (Sandbox Code Playgroud)
<h1>Heading</h1>
<a class="button" href="#">The "Button"</a>
<h1>Another Heading</h1>Run Code Online (Sandbox Code Playgroud)
我们将H1的颜色设置为绿色色调,并将A的颜色设置为H的兄弟色!偏红(前2条规则).第三条规则符合我的描述 - 当H1悬停时改变A颜色.
但是请注意第四条规则a:hover h1只改变了H1的背景色如下锚,而不是它前面的一个.
Eri*_*ric 13
没有CSS选择器可以做到这一点(在CSS3中,甚至).在CSS中,元素永远不会知道它们的父元素,所以你不能这样做a:parent h1(例如).他们也不知道他们的兄弟姐妹(在大多数情况下),所以你做不到#container a:hover { /* do something with sibling h1 */ }.基本上,CSS属性不能修改除元素及其子元素之外的任何内容(它们不能访问父母或兄弟姐妹).
你可以包含h1 内的a,但是这会使你的h1hoverable为好.
您只能使用JavaScript(jsFiddle概念验证)来实现这一目标.这看起来像是这样的:
$("a.button").hover(function() {
$(this).siblings("h1").addClass("your_color_class");
}, function() {
$(this).siblings("h1").removeClass("your_color_class");
});
Run Code Online (Sandbox Code Playgroud)
Html:
<div id="banner">
<h1>Heading</h1>
<a class="button" href="#">link</a>
</div>?
Run Code Online (Sandbox Code Playgroud)
CSS:
?#banner:hover h1 {
color: red;
}
#banner h1:hover {
color: black;
}
a {
position: absolute;
}
Run Code Online (Sandbox Code Playgroud)
小提琴:http://jsfiddle.net/joplomacedo/77mqZ/
该a元素绝对定位.对于你现有的结构,可能并不完美.让我知道,我可能会找到一个解决方法.
小智 6
只需几行 CSS 和一些基本的Flexbox了解,确实可以实现这一点。
正如Stephen P 在他的回答中所说,相邻兄弟组合器确实选择紧随其后的兄弟姐妹。为了实现OP的要求,您可以使用两种灵活的方法:
方法 1(使用“flex-flow”简写属性)
.flex-parent {
display: flex;
flex-flow: column-reverse wrap
}
.flex-child-1:hover + .flex-child-2 {
color: #FF3333;
}Run Code Online (Sandbox Code Playgroud)
<div class="flex-parent">
<a class="flex-child-1">Hover me</a>
<h1 class="flex-child-2">I am changing color</h1>
</div>Run Code Online (Sandbox Code Playgroud)
方法 2(使用“order”属性和多个子项)
.flex-parent {
display: flex;
flex-direction: column;
}
.flex-child-1 {
order: 2;
}
.flex-child-2 {
order: 1;
}
.flex-child-3 {
order: 3;
}
.flex-child-1:hover+.flex-child-2 {
color: #FF3333;
}Run Code Online (Sandbox Code Playgroud)
<div class="flex-parent">
<h1 class="flex-child-3">I am not changing color</h1>
<a class="flex-child-1">Hover me</a>
<h1 class="flex-child-2">I am changing color</h1>
</div>Run Code Online (Sandbox Code Playgroud)
奖金:
试试这个单行纯 CSS 解决方案:
.parent:hover .child:not(:hover) {
/* this style affects all the children *except* the one you're hovering over */
color: red;
}
Run Code Online (Sandbox Code Playgroud)
更多信息在这里: https: //codyhouse.co/nuggets/styling-siblings-on-hover