Controlling CSS based hover effects

2019-09-09 11:16发布

问题:

To my knowledge, the answer to this is no, can't be done, but I need a second opinion:

If I have the following:

<li>
    <a >#</a>
    <div class="sub">
    #
    </div>
</li>

and have a background image that appears on li a:hover is it possible to have that background stay on when hovering on the .sub div? This also has to work pure CSS - no javascript cheats.

My understanding is because .sub isn't a child of the a we can't reference it in css to keep the hover.

Because the image is for only one section of the code, I can't move it to the li and reference li:hover a.

回答1:

Not sure what all you are trying to achieve, but there are many hover effects that can be done.

SECOND UPDATE: If you don't need to interact (other a tags, etc) at all with anything in the div, then this way cheats to get the effect. Note how the anchor inside the div does not register because of the z-index.

UPDATE I think I understand your issue better now. Can you add a wrapper and do the following?:

Example HTML:

<ul>
  <li>
    <div>  
      <a>Some anchor text</a>
      <div class="sub">Some div content <a>and anchor</a></div>
    </div>
  </li>
</ul>

Example CSS:

li:hover {
    background-color: cyan;
}


li > div:hover > a {
    background-color: green;
}

a:hover {
    color: yellow;
    display: block;
}

a:hover + .sub {
    outline: 1px solid blue;
}

.sub:hover {
    color: red;
    outline: 1px solid red;
}


回答2:

If you can't use a class on the li or modify the div.sub to be in the a, you're probably out of luck without Javascript:

Is there a CSS parent selector?

However, if you can, you could use:

<ul>
  <li class="sub">
      <a>Class #</a>
      <div class="sub">#</div>
  </li>
  <li>
      <a>Inner #
          <div class="sub">#</div>
      </a>
  </li>
  <li>
      <a>None #</a>
      <div class="sub">#</div>
  </li>
</ul>

li.sub:hover,
li a:hover {
    background: url(http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=32&d=identicon&r=PG);
}
li a {
    border: 1px solid blue;
    display: block;
}
.sub {
    border: 1px solid green;
}

http://jsfiddle.net/B7Au2/4/



回答3:

I don't know if you can modify the html, but if you can, try swapping the div and the a:

<li>
    <div class="sub">
    #
    </div>
    <a >#</a>
</li>

Now you can use the adjacent sibling selector:

li a:hover, li .sub:hover + a {background:url('some-image.png')}

Unfortunately there's no way to select the previous element through CSS: that's why you need to swap your elements.



标签: css hover