David Skx
David Skx

Reputation: 131

CSS Transition between children

Quick question. Does transition work if I hover over a child to target another child, or one separate div with another separate div?

I can only get transition to work if I put the children in a container and hover over the parent. What are the rules to this?

Example 1 (Doesn't work):

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  display: flex;
  justify-content: center;
}

.underline {
  width: 0px;
  height: 2px;
  background-color: black;
  transition: 0.4s;
}

h2:hover .underline {
  width: 165px;
}
<body>

    <h2>Hover Over Me</h2>
    <div class="underline"></div>

</body>

Example 2 (Doesn't work)

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  display: flex;
  justify-content: center;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 180px;
  height: 50px;
}

.underline {
  width: 0px;
  height: 2px;
  background-color: black;
  transition: 0.4s;
}

h2:hover .underline {
  width: 165px;
}
<body>

  <div class="container">
    <h2>Hover Over Me</h2>
    <div class="underline"></div>
  </div>

</body>

Example 3 (Works)

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  display: flex;
  justify-content: center;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 180px;
  height: 50px;
}

.underline {
  width: 0px;
  height: 2px;
  background-color: black;
  transition: 0.4s;
}

.container:hover .underline {
  width: 165px;
}
<body>

  <div class="container">
    <h2>Hover Over Me</h2>
    <div class="underline"></div>
  </div>

</body>

Upvotes: 0

Views: 63

Answers (1)

Osman Durdag
Osman Durdag

Reputation: 955

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  display: flex;
  justify-content: center;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 180px;
  height: 50px;
}

.underline {
  width: 0px;
  height: 2px;
  background-color: black;
  transition:0.4s;
}

h2:hover + .underline {
  width: 165px;
}
<body>

  <div class="container">
    <h2>Hover Over Me</h2>
    <div class="underline"></div>
  </div>

</body>

You can check This for css selectors

Upvotes: 1

Related Questions