Как при hover изменить другой элемент

I have looked at several other questions but I can't seem to figure any of them out, so here is my problem: I would like to have a div or a span, when you hover over it an area would appear and wou...

I have looked at several other questions but I can’t seem to figure any of them out, so here is my problem: I would like to have a div or a span, when you hover over it an area would appear and would be like a drop down.

Such as I have an div, and I want to hover over it and have it show some info about the item I hovered over

<html>
<head>
<title>Question1</title>
<styles type="css/text">

  #cheetah {
      background-color: red;
      color: yellow;
      text-align: center;
  }

  a {
      color: blue;
  }

  #hidden {
      background-color: black;
   }

   a:hover > #hidden {
      background-color: orange;
      color: orange;
  }
</styles>

</head>
<body>
  <div id="cheetah">
     <p><a href="#">Cheetah</a></p>
  </div>
  <div id="hidden">
     <p>A cheetah is a land mammal that can run up 2 60mph!!!</p>
  </div>
</body>
</html>

But this ^ doesn’t seem to work, I don’t know why… and if there is a way to do that in CSS, I would like to know, but I want any and all suggestions.

Minal Chauhan's user avatar

asked Dec 23, 2011 at 9:43

Neros's user avatar

2

You can achieve this in CSS only if the hidden div is a child of the element you use for hovering:

http://jsfiddle.net/LgKkU/

answered Dec 23, 2011 at 9:52

ptriek's user avatar

ptriekptriek

8,9304 gold badges31 silver badges29 bronze badges

You cannot affect a non-child element using :hover from within CSS2, which is supported by all common browsers.

You can affect a sibling element using CSS2.1 selectors, like so:

a:hover + .sibling { ... }

However, this only works for direct siblings. This means you could have HTML like this:

<p><a href="#">Cheetah</a> <span class="sibling">Blah Blah Blah</span></p>

Notice that the a and the span are direct siblings.

Here’s a fiddle showing the siblings working: http://jsfiddle.net/vUUxp/

However, not all browsers support the CSS2.1 sibling selectors, so you need to decide based on your target audience if you can use this or not.

Edit: Corrected my mistake on the CSS version for the + selector: it’s 2.1 that defines it, not CSS3. I also added a link showing browser support. Otherwise, the answer is the same.

answered Dec 23, 2011 at 9:55

OverZealous's user avatar

OverZealousOverZealous

39.1k15 gold badges97 silver badges100 bronze badges

1

Or, if you’re open to it, use jQuery.

Something like this would work:

$("#element") // select your element (supports CSS selectors)
    .hover(function(){ // trigger the mouseover event
        $("#otherElement") // select the element to show (can be anywhere)
            .show(); // show the element
    }, function(){ // trigger the mouseout event
        $("#otherElement") // select the same element
            .hide(); // hide it
    });

And remember to wrap this in a DOM ready function ($(function(){...}); or $(document).ready(function(){...});).

answered Dec 23, 2011 at 9:56

Purag's user avatar

PuragPurag

16.9k4 gold badges53 silver badges74 bronze badges

You can absolutely do this in CSS3 now using the ~ adjacent sibling selector.

triggerSelector:hover ~ targetSelector {
    display: block;
}

For example, if you want a tooltip to appear when hovering over an adjacent button:

.button:hover ~ .tooltip {
    display: block;
}

answered Nov 6, 2018 at 0:17

brandonscript's user avatar

brandonscriptbrandonscript

66.4k30 gold badges157 silver badges216 bronze badges

I have looked at several other questions but I can’t seem to figure any of them out, so here is my problem: I would like to have a div or a span, when you hover over it an area would appear and would be like a drop down.

Such as I have an div, and I want to hover over it and have it show some info about the item I hovered over

<html>
<head>
<title>Question1</title>
<styles type="css/text">

  #cheetah {
      background-color: red;
      color: yellow;
      text-align: center;
  }

  a {
      color: blue;
  }

  #hidden {
      background-color: black;
   }

   a:hover > #hidden {
      background-color: orange;
      color: orange;
  }
</styles>

</head>
<body>
  <div id="cheetah">
     <p><a href="#">Cheetah</a></p>
  </div>
  <div id="hidden">
     <p>A cheetah is a land mammal that can run up 2 60mph!!!</p>
  </div>
</body>
</html>

But this ^ doesn’t seem to work, I don’t know why… and if there is a way to do that in CSS, I would like to know, but I want any and all suggestions.

Minal Chauhan's user avatar

asked Dec 23, 2011 at 9:43

Neros's user avatar

2

You can achieve this in CSS only if the hidden div is a child of the element you use for hovering:

http://jsfiddle.net/LgKkU/

answered Dec 23, 2011 at 9:52

ptriek's user avatar

ptriekptriek

8,9304 gold badges31 silver badges29 bronze badges

You cannot affect a non-child element using :hover from within CSS2, which is supported by all common browsers.

You can affect a sibling element using CSS2.1 selectors, like so:

a:hover + .sibling { ... }

However, this only works for direct siblings. This means you could have HTML like this:

<p><a href="#">Cheetah</a> <span class="sibling">Blah Blah Blah</span></p>

Notice that the a and the span are direct siblings.

Here’s a fiddle showing the siblings working: http://jsfiddle.net/vUUxp/

However, not all browsers support the CSS2.1 sibling selectors, so you need to decide based on your target audience if you can use this or not.

Edit: Corrected my mistake on the CSS version for the + selector: it’s 2.1 that defines it, not CSS3. I also added a link showing browser support. Otherwise, the answer is the same.

answered Dec 23, 2011 at 9:55

OverZealous's user avatar

OverZealousOverZealous

39.1k15 gold badges97 silver badges100 bronze badges

1

Or, if you’re open to it, use jQuery.

Something like this would work:

$("#element") // select your element (supports CSS selectors)
    .hover(function(){ // trigger the mouseover event
        $("#otherElement") // select the element to show (can be anywhere)
            .show(); // show the element
    }, function(){ // trigger the mouseout event
        $("#otherElement") // select the same element
            .hide(); // hide it
    });

And remember to wrap this in a DOM ready function ($(function(){...}); or $(document).ready(function(){...});).

answered Dec 23, 2011 at 9:56

Purag's user avatar

PuragPurag

16.9k4 gold badges53 silver badges74 bronze badges

You can absolutely do this in CSS3 now using the ~ adjacent sibling selector.

triggerSelector:hover ~ targetSelector {
    display: block;
}

For example, if you want a tooltip to appear when hovering over an adjacent button:

.button:hover ~ .tooltip {
    display: block;
}

answered Nov 6, 2018 at 0:17

brandonscript's user avatar

brandonscriptbrandonscript

66.4k30 gold badges157 silver badges216 bronze badges

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    In this article, we will see how to affect other elements when one element has hovered using CSS. if we define 2 HTML elements where we want to hover over one element & at the same moment want to change the style of another element then both the elements should be directly related as either parent-child or sibling, which indicates either one element must be inside another element or both elements should be within the same target element so that the hover effect can be seen. Hover is used to add styling to the elements when the mouse hovers over them, i.e. when you place your cursor over the element then some text will appear which tells you about the functionality of that element. It is generally used for navigation when the UI of any website or software is complex.

    Approach: This task can be accomplished by adding one element inside the other element & accordingly declaring the required CSS properties for the parent-child elements, so that whenever hovering outside the element then automatically the property of the inner element will change.

    Example 1: In the below example, we will see how other element gets affected when we hover over one element.

    HTML

    <!DOCTYPE html>

    <html>

    <head>

        <style>

            body {

                text-align: center;

            }

            h1 {

                color: green;

            }

            .parent {

                width: 600px;

                height: 200px;

                background-color: lightgrey;

            }

            .child {

                margin-left: 45px;

                width: 100px;

                height: 30px;

                background-color: grey;

            }

            div {

                outline: 1px solid green;

            }

            .parent:hover .child {

                background-color: green;

            }

        </style>

    </head>

    <body>

        <h1>GeeksforGeeks</h1>

        <h3>

            Hovering one element to change 

            the effect to other element

        </h3>

        <div class="parent"> GeeksforGeeks

            <div class="child">

                GeeksforGeeks 

            </div>

            <br>

            <div class="child">

                GeeksforGeeks 

            </div>

            <br>

            <div class="child">

                GeeksforGeeks 

            </div>

        </div>

    </body>

    </html>

    Explanation: In the above example, we have made two div elements named parent and child. If we hover over the parent element then automatically it will affect the child element.

    Output: 

    Example 2: In the below example, we will create two div elements. When you hover on one element then other elements will change their property.

    HTML

    <!DOCTYPE html>

    <html>

    <head>

        <style>

            body {

                text-align: center;

            }

            h1 {

                color: green;

            }

            .parent {

                width: 600px;

                height: 200px;

                background-color: lightgrey;

            }

            .child {

                width: 30px;

                height: 30px;

                background-color: grey;

            }

            div {

                outline: 1px solid black;

            }

            .parent:hover .child {

                background-color: green;

            }

            .child {

                background-color: #4CAF50;

                border: none;

                color: white;

                padding: 50px 160px;

                margin-top: 50px;

                text-align: center;

                text-decoration: none;

                display: inline-block;

                font-size: 16px;

            }

        </style>

    </head>

    <body>

        <h1>GeeksforGeeks</h1>

        <h3>

            Element's property will change when 

            hovering to other element

        </h3>

        <div class="parent">

            <button class="child">

                GeeksforGeeks 

            </button>

        </div>

    </body>

    </html>

    Output:

    Селектор :hover определят стиль элемента при наведении курсора мыши. Этот селектор можно использовать для всех элементов, а не только для ссылок. Псевдокласс CSS :hover запускается, когда пользователь наводит указатель мыши на элемент.

    Стили, определяемые активами псевдо-класса, будут переопределены любым последующим классом. Например, :link, :active или :visited, который имеет хотя бы один равный атрибут. Поэтому используйте псевдокласс hover после :link и :visit, но перед :active.

    Пример ссылок с разными стилями:

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    a.model1:hover, a.model1:active {color: purple;}
    a.model2:hover, a.model2:active {font-size: 210%;}
    a.model3:hover, a.model3:active {background: yellow;}
    a.model4:hover, a.model4:active {font-family: arial;}
    a.model5:visited, a.model5:link {text-decoration: none;}
    a.model5:hover, a.model5:active {text-decoration: underline;}
    </style>
    </head>
    <body>
    <p>Move your mouse over links to notice the changes.</p>
    <p><a class="model1" href="default.asp">This link will change its color</a></p>
    <p><a class="model2" href="default.asp">This link will change its font-size</a></p>
    <p><a class="model3" href="default.asp">This link will change its background-color</a></p>
    <p><a class="model4" href="default.asp">This link will change its font-family</a></p>
    <p><a class="model5" href="default.asp">This link will change its text-decoration</a></p>
    </body>
    </html>
    • Выпадающее меню
    • Другой стиль
    • Нижняя граница становится фоном
    • Уменьшение интенсивности цвета
    • Увеличение ширины и высоты
    • Вращение элемента
    • Изменение формы элемента
    • Изменение цвета границ
    • Заключение

    Пример применения псевдокласса к элементу <span>. Эффект проявляется при наведении курсора на элемент <div>:

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    div {
      background-color: Gainsboro;
      padding: 30px;
      display: none;
      font-size: 40px;
    }
    span:hover + div {
      display: block;
    }
    </style>
    </head>
    <body>
    <span>Please, hover over me!</span>
    <div>This is the expected result</div>
    </body>
    </html>

    Пример, в котором мы будем отображать выпадающее меню при наведении курсора мыши:

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    div {background-color: Gainsboro;}
    div a {
      text-decoration: none;
      color: black;
      font-size: 24px;
      padding: 12px;
      display:inline-block;
    }
    ul {
      display: inline;
      margin: 0;
      padding: 0;
    }
    ul li {display: inline-block;}
    ul li:hover {background: Grey;}
    ul li:hover ul {display: block;}
    ul li ul {
      position: absolute;
      width: 200px;
      display: none;
    }
    ul li ul li { 
      background: Grey; 
      display: block; 
    }
    ul li ul li a {display:block;} 
    ul li ul li:hover {background: LightGrey;}
    </style>
    </head>
    <body>
    <div>
      <a href="1">Link without hover effect</a>
      <ul>
        <li>
          <a href="1">Link with hover effect(drop-down)</a>
          <ul>
            <li><a href="1">Bundle 1</a></li>
            <li><a href="1">Bundle 2</a></li>
            <li><a href="1">Bundle 3</a></li>
          </ul>
        </li>
      </ul>
    </div>
    </body>
    </html>

    Еще один пример эффекта при наведении, но уже с другим стилем:

    <!DOCTYPE html>
    <html>
    <head>
    <style>
     body {
      align-items: center;
      display: flex;
      height: 100px;
      justify-content: left;
    }
    a {
      border-bottom: 1px solid Gainsboro;
      color: Grey;
      padding-bottom: .15em;
      text-decoration: none;
    }
    a:hover {
    background-image: url("data:image/svg+xml;charset=utf8,%3Csvg id='squiggle-link' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:ev='http://www.w3.org/2001/xml-events' viewBox='0 0 20 4'%3E%3Cstyle type='text/css'%3E.squiggle{animation:shift .3s linear infinite;}@keyframes shift {from {transform:translateX(0);}to {transform:translateX(-20px);}}%3C/style%3E%3Cpath fill='none' stroke='%23453886' stroke-width='2' class='squiggle' d='M0,3.5 c 5,0,5,-3,10,-3 s 5,3,10,3 c 5,0,5,-3,10,-3 s 5,3,10,3'/%3E%3C/svg%3E");
      background-position: bottom;
      background-repeat: repeat-x;
      background-size: 30%;
      border-bottom: 10;
      padding-bottom: .5em;
      text-decoration: none;
    }
    </style>
    </head>
    <body>
    <a href="#">CSS hover effect</a>
    </body>
    </html>

    Пример, в котором при наведении курсора на ссылку нижняя граница строки увеличивается и становится фоном:

    <!DOCTYPE html>
    <html>
    <head>
    <style>
     :root {
      --Color: Khaki ;
    }
    body {
      align-items: center;
      display: flex;
      font-family: arial;
      font-size: 35px;
      height: 100vh;
      justify-content: center;
    }
    a {
      background:
         linear-gradient(
           to bottom, var(--Color) 0%,
           var(--Color) 100%
         );
        background-position: 0 100%;
        background-repeat: repeat-x;
        background-size: 5px 5px;
      color: grey;
      text-decoration: none;
      transition: background-size .2s;
    }
    a:hover {
      background-size: 4px 50px;
    }
    </style>
    </head>
    <body>
    <p>Try not to become a man of success, but rather try  <a href="1">to become a man of value</a></p>
    </body>
    </html>

    Эффект :hover, который проявляется уменьшением интенсивности цвета. Это отличный способ привлечь внимание к важному элементу на странице:

    <!DOCTYPE html>
    <html>
    <head>
    <link href="http://fonts.googleapis.com/css?family=Lato:900" rel="stylesheet" type="text/css">
    <style type="text/css">
    body > div
         {
                 
                margin:121px 149px;
                 
                width:483px;
                height:298px;
                 
                background:#676470;
                color:Grey;
                 
                font-family:Lato;
                font-weight:900;
                font-size:3.4em;
                 
                text-align:center;
                line-height:298px;
                 
                transition:all 0.3s;
                 
            }
             
            .decolor
            {
                opacity:0.5;
            }
            .decolor:hover
            {
                opacity:1;
            }
    </style>
    </head>
    <body>
    <div class="decolor">DECOLOR</div>
    </body>
    </html>

    Вы можете использовать свойство transform для увеличения ширины и высоты элемента при наведении курсора:

    <!DOCTYPE html>
    <html>
    <head>
    <link href="http://fonts.googleapis.com/css?family=Lato:900" rel="stylesheet" type="text/css">
    <style type="text/css">
    body > div
         {
                 
                margin:121px 149px;
                width:483px;
                height:298px;
                background:#676470;
                color:Gainsboro ;
                font-family:Helvetica;
                font-weight:900;
                font-size:3.4em;
                text-align:center;
                line-height:298px;
                transition:all 0.3s;
            }
            .grow:hover
    {
            -webkit-transform: scale(1.3);
            -ms-transform: scale(1.3);
            transform: scale(1.3);
    }
    </style>
    </head>
    <body>
    <div class="grow">Grow Effect</div>
    </body>
    </html>

    CSS-преобразования также можно использовать для реализации эффекта вращения элемента

    <!DOCTYPE html>
    <html>
    <head>
    <link href="http://fonts.googleapis.com/css?family=Lato:900" rel="stylesheet" type="text/css">
    <style type="text/css">
    body > div
         {    
                margin:121px 149px;            
                width:483px;
                height:298px;            
                background:#676470;
                color:Gainsboro ;
                 
                font-family:Helvetica;
                font-weight:900;
                font-size:3.4em;            
                text-align:center;
                line-height:298px;            
                transition:all 0.3s;            
            }      
         .rotate:hover
    {
            -webkit-transform: rotateZ(-30deg);
            -ms-transform: rotateZ(-30deg);
            transform: rotateZ(-30deg);
    }
    </style>
    </head>
    <body>
    <div class="rotate">Rotate Effect</div>
    </body>
    </html>

    Еще один популярный эффект – превращение круглого элемента в квадратный и наоборот

    <!DOCTYPE html>
    <html>
    <head>
    <link href="http://fonts.googleapis.com/css?family=Lato:900" rel="stylesheet" type="text/css">
    <style type="text/css">
    body > div
         {    
                margin:121px 149px;            
                width:483px;
                height:298px;            
                background:#676470;
                color:Gainsboro ;
                font-family:Helvetica;
                font-weight:900;
                font-size:48px;            
                text-align:center;
                line-height:298px;            
                transition:all 0.3s;            
            }      
         .circle:hover
    {
            border-radius:70%;
    }
    </style>
    </head>
    <body>
    <div class="circle">Square to circle</div>
    </body>
    </html>

    Еще один интересный эффект – изменение цвета границ элемента при наведении курсора. Для его реализации применяется переход с использованием тени для блока:

    <!DOCTYPE html>
    <html>
    <head>
    <link href="http://fonts.googleapis.com/css?family=Lato:900" rel="stylesheet" type="text/css">
    <style type="text/css">
    body > div
         {    
                margin:121px 149px;            
                width:483px;
                height:298px;            
                background:#676470;
                color:Gainsboro ;
                 
                font-family:Helvetica;
                font-weight:900;
                font-size:48px;            
                text-align:center;
                line-height:298px;            
                transition:all 0.3s;            
            }      
         .border:hover
    {
            box-shadow: inset 0 0 0 25px Lavender ;
    }
    </style>
    </head>
    <body>
    <div class="border">BORDER</div>
    </body>
    </html>

    Поддержка браузерами: Google Chrome, Microsoft Edge, Firefox, Opera, Safari.

    CSS3 позволяет создавать множество красивых эффектов без использования Java Script. Это доказывают приведенные выше примеры.

    Понравилась статья? Поделить с друзьями:
  • Как премьер про изменить размер холста
  • Как предложить жене изменить
  • Как предательство может изменить человека
  • Как практически можно изменить параметры шрифта
  • Как правильное питание изменило мою жизнь