Select sibling div over current div

I am trying to make a harmonic effect by changing the height of the divs while hovering over another.

My HTML looks like this:

<html><body> <div class="section1"></div> <div class="section2"></div> <div class="section3"></div> <div class="section4"></div> </body></html> 

Each section has a height of 25%. When hovering over section 1, all other divs should decrease in size, while section1 expands. This is easy to do with the following CSS:

 .section1 { height: 40%; } .section1:hover ~ div:not(section1) { height: 20%; } 

The problem is that ~ selector selects only divs div divs below the current div. Therefore, if I use the same code for section 2, this will only affect section3 and section4. Section 1 will have an original height of 25% because it is taller than the current div.

Is it possible to solve this problem only with CSS?

+4
source share
3 answers

Yes. Place a wrapper around your sections and reduce their height when you hover over the wrapper. Then increase the height of one section on which you are hanging.

Demo

HTML becomes:

 <div class='section-wrapper'> <div class="section1"></div> <div class="section2"></div> <div class="section3"></div> <div class="section4"></div> </div> 

Matching CSS :

 .section-wrapper { height: 500px; } .section-wrapper div { height: 25%; outline: dotted 1px; } .section-wrapper:hover div { height: 20%; } .section-wrapper div:hover { height: 40%; } 
+4
source

Try this

HTML

 <html> <body> <div class="container"> <div class="section1">1</div> <div class="section2">2</div> <div class="section3">3</div> <div class="section4">4</div> </div> </body> </html> 

CSS

 .container:hover div { height:20px; } .container .section1,.container .section1:hover, .container .section2,.container .section2:hover, .container .section3,.container .section3:hover, .container .section4,.container .section4:hover{ height: 50px; }​ 
0
source

Simple Add parent container to sections

 <div class="parent"> <div class="section1">section1</div> <div class="section2">section2</div> <div class="section3">section3</div> <div class="section4">section4</div> </div 

And create them like

 .parent div{height: 25%; border:solid 1px #f00} .parent:hover div{height: 20%; } .parent div:hover {height: 40%; } 
0
source

Source: https://habr.com/ru/post/1432252/


All Articles