Rushan
Rushan

Reputation: 105

select previous element and apply effect using css

I have 3 <div>s in one horizontal line. each width = 33.33% and I want to change width of one div on hover to 50% and other two to 25%.

<div id="A"></div>
<div id="B"></div>
<div id="C"></div>

I can apply this for A as

#A:hover{width:50%}
#A:hover+#B
{width:25%}
#A:hover~#C
{width:25%}

and it work fine.

when we hover B

#B:hover{width:50%}
#B:hover+#A
{width:25%}
#B:hover~#C
{width:25%}

B expand to 50% and C shrink to 25%. but #A remain 33.33%.

How can I fix this.

Upvotes: 0

Views: 75

Answers (2)

Paulie_D
Paulie_D

Reputation: 115288

Flexbox can do that without a parent selctor:

* {
  box-sizing: border-box;
}
.parent {
  width: 80%;
  margin: 1em auto;
  display: flex;
}
.child {
  height: 150px;
  border: 1px solid grey;
  flex: 1;
  transition: flex 1s ease;
}
.child:hover {
  flex: 0 0 50%;
}
<div class="parent">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>

Upvotes: 1

Vitorino fernandes
Vitorino fernandes

Reputation: 15971

In Css there is no previous selectors

  • by default the width is 33.33%
  • on hover of the parent the width is changed to 25%
  • on hover of the div inside the width is changed to 50%

* {
  box-sizing: border-box;
}
.par {
  overflow: hidden; /* to clear floats */
}
.par div {
  width: 33.33%; /* default width */
  transition: .2s linear;
  border: 1px solid red;
  height: 100px;
  float: left;
}
.par:hover div {
  width: 25%; /* width when you hover on parent */
}
.par div:hover {
  width: 50% /* width when you hover on the element */
}
<div class="par">
  <div id="A">1</div>
  <div id="B">2</div>
  <div id="C">3</div>
</div>

Upvotes: 5

Related Questions