user3666471
user3666471

Reputation: 945

Make a element visible when another element is hovered

I'm trying to make text appear below an image when it is being hovered upon, but can't get the syntax right. I'm beginning to learn CSS, so I may not be following the best practices, please point out how I can solve my problem better!

<div class="X">
    <span class="Y">
        <a href="XYZ">
            <span class="A"></span>
        </a>
        <span class="A-element">A</span>
    </span>
    <span class="Y">
        <a href="XYZ">
            <span class="B"></span>
        </a>
        <span class="B-element">B</span>
    </span>
</div>

My CSS looks like this:

.X { 
  font-size: 5em;
}

.Y {
  margin-left: 0.5em;
  margin-right: 0.5em;
}

.A-element {
  display: none;
}

.B-element {
  display: none;
}

.A {
  color: #fff;
}

.B {
  color: #fff;
}

.A:hover .A-element {
    color: #ccc;
    display: block;
}

.B:hover .B-element {
    color: #ccc;
    display: block;
}

Upvotes: 0

Views: 138

Answers (2)

Ararat Harutyunyan
Ararat Harutyunyan

Reputation: 926

you can use hover on parent element. for example

.Y:hover .A-element {
    color: #ccc;
    display: block;
}

Upvotes: 1

James Donnelly
James Donnelly

Reputation: 128791

Hovering over .A to change the style of .A-element isn't possible with CSS because to do this we'd have to first select the parent of .A, and CSS has no parent selector.

What is possible, however, is to instead place the hover on the a element within your .Y element, and use the + adjacent sibling combinator to select the element next to it:

.Y a:hover + span + span {
    color: #ccc;
    display: block;
}

As you can see, I haven't had to use the .A-element or .B-element classes at all as this will apply to both your .A-element and .B-element elements.


Simplified Code Snippet

.Y a:hover + span {
  background: tomato;
  color: #fff;
  padding: 0 20px;
}
<div class="X">
    <span class="Y">
        <a href="XYZ">
            <span class="A">Hover here</span>
        </a>
        <span class="A-element">A</span>
    </span>
    <span class="Y">
        <a href="XYZ">
            <span class="B">Hover here</span>
        </a>
        <span class="B-element">B</span>
    </span>
</div>

Upvotes: 1

Related Questions