apdm apdm - 1 month ago 5
CSS Question

How can I make the first sibling element have blue background except for when a different sibling element is hovered?

I have the following elements:

<div>Timothy Gruns</div>
<div>Lawrence Fishly</div>
<div>Jackson Crolya</div>


I want the background color to change to blue when hovered, but if none of them are hovered, I would like the first element to be blue. So by default it would look like this:

enter image description here

If the 3rd element was hovered it would look like this:

enter image description here

Answer

If you wrap all 3 divs in a container you can use the :first-child and the :hover selectors to achieve this:

div.container > div {
  border: 1px solid black;
  margin: 5px;
  padding: 5px;
}
div.container > div:first-child {
  background: blue;
}
div.container:hover > div {
  background: white;
}
div.container > div:hover {
  background: red;
}
<div class="container">
  <div>Timothy Gruns</div>
  <div>Lawrence Fishly</div>
  <div>Jackson Crolya</div>
</div>

  1. Set the border/margin/padding for the inner divs.
  2. Set default background of the first inner-div is blue.
  3. When hovering the container - all inner divs gets white background
  4. When hovering a div inside the container - that div gets a red background.

You can set your own colors :) this is just for the example.

Comments