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

Как сделать так, чтобы при наведении на один элемент (hover) менять стили другого элемента? Можно ли это сделать только на css? К примеру: навожу на блок и хочу чтобы все заголовки в этом блоке стали

К сожалению, этот код не будет работать, так как селектор .block h1 обращается к всем заголовкам h1 внутри элемента с классом block, независимо от того, наведен ли курсор на этот элемент.

Чтобы сделать то, что вы хотите, нужно использовать селектор дочернего элемента (>):

.block:hover > h1 {
    color: red;
}

Этот селектор обращается только к заголовкам h1, которые являются дочерними элементами элемента с классом block, и изменяет их стиль только тогда, когда курсор наведен на этот элемент.

Пример HTML-разметки:

<div class="block">
    <h1>Заголовок</h1>
</div>

Также можно использовать псевдокласс :hover на самом заголовке, чтобы изменить его стиль при наведении на родительский элемент:

.block h1:hover {
    color: red;
}

Вот пример HTML-разметки с несколькими элементами, которые меняют свои стили при наведении на другие элементы:

<style>
    /* Изменяет цвет текста всех заголовков h1 внутри элемента с классом block */
    .block:hover > h1 {
        color: red;
    }

    /* Изменяет цвет фона элемента с классом block, когда курсор наведен на заголовок h1 */
    h1:hover + .block {
        background-color: lightgrey;
    }

    /* Изменяет цвет фона элемента с классом block, когда курсор наведен на элемент с классом link */
    .link:hover ~ .block {
        background-color: lightblue;
    }
</style>

<!-- Элементы, которые будут изменять свои стили при наведении -->
<h1>Заголовок</h1>
<a href="#" class="link">Ссылка</a>
<div class="block">
    <h1>Внутренний заголовок</h1>
</div>

В первом случае цвет текста всех заголовков h1 внутри элемента с классом block становится красным, когда курсор наведен на этот элемент.

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:

    TerribleVoice

    0 / 0 / 0

    Регистрация: 28.02.2018

    Сообщений: 25

    1

    28.02.2018, 21:45. Показов 6329. Ответов 2

    Метки нет (Все метки)


    Есть 2 элемента, нужно чтобы при наведении на любой из них менялись оба
    код

    HTML5
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
    </head>
    <body>
    <div class="wrapper">
      <div class = "name"><p class="text">TExt</p></div>
      <div class = "logo"></div>
      </div>
    </body>
    </html>
    CSS
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    
    .logo{
      background-color: #ccc;
      width: 100px;
      height: 20px;
      display: inline-block;
    }
    .name { 
      display: inline-block;
      padding-bottom: 10px;
      
    }
    .logo:hover{
      border: 1px red solid;
    }
     
    .logo:hover .name{
      border: 1px red solid;
    }

    __________________
    Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



    0



    Qwerty_Wasd

    dev — investigator

    Эксперт JSЭксперт HTML/CSS

    2148 / 1493 / 651

    Регистрация: 16.04.2016

    Сообщений: 3,696

    28.02.2018, 22:24

    2

    TerribleVoice,

    Цитата
    Сообщение от TerribleVoice
    Посмотреть сообщение

    при наведении на любой из них менялись оба

    только скриптом. На чистом CSS возможен только такой вариант (стили из вашей песочницы)

    CSS
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    
    .logo{
      background-color: #ccc;
      width: 100px;
      height: 20px;
      display: inline-block;
    }
    .name { 
      display: inline-block;
      padding-bottom: 10px;
      
    }
    .logo:hover{
      border: 1px red solid;
    }
     
    .name:hover{
      border: 1px red solid;
    }
    .name:hover~.logo{
      border: 1px red solid;
    }

    Добавлено через 8 минут
    Если JS не проблема, вот вариант- песочница

    CSS
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    
    .logo{
      background-color: #ccc;
      width: 100px;
      height: 20px;
      display: inline-block;
    }
    .name { 
      display: inline-block;
      padding-bottom: 10px;
      
    }
    .logo:hover{
      border: 1px red solid;
    }
     
    .name:hover{
      border: 1px red solid;
    }
    .name:hover~.logo{
      border: 1px red solid;
    }
    Javascript
    1
    2
    
    document.querySelector('.logo').onmouseover=function(){document.querySelector('.name').style.cssText="border:1px red solid"}
    document.querySelector('.logo').onmouseout=function(){document.querySelector('.name').style.cssText=""}



    0



    AlexZaw

    Эксперт HTML/CSS

    2030 / 1476 / 595

    Регистрация: 07.08.2016

    Сообщений: 3,643

    01.03.2018, 00:23

    3

    Поизвращался малость, сделал на чистом css:

    HTML5
    1
    2
    3
    4
    5
    6
    7
    8
    
    <div class="wrapper">
      <div class = "name"><p class="text">TExt</p></div>
      <div class = "logo"></div>
     
      <div class="inner">
          <div class = "name"><p class="text">TExt</p></div>  
      </div>
    </div>
    CSS
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    
    .wrapper{
      position: relative;
    }
     
    .logo{
      background-color: #ccc;
      width: 100px;
      height: 20px;
      display: inline-block;
      margin-left: 10px;
    }
     
    .name{ 
      display: inline-block;
      padding-bottom: 10px;  
    }
     
    .logo:hover {
      outline: 1px red solid;
    }
     
    .logo:hover ~.inner>.name{
      outline: 1px red solid;
    }
     
    .name:hover {
        outline: 1px red solid;
    }
     
    .name:hover ~.logo{
        outline: 1px red solid;
    }
     
    .inner{
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      z-index: -1;
    }



    1



    IT_Exp

    Эксперт

    87844 / 49110 / 22898

    Регистрация: 17.06.2006

    Сообщений: 92,604

    01.03.2018, 00:23

    3

    Селектор :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. Это доказывают приведенные выше примеры.

    Как сделать так, чтобы при наведении на один элемент (hover) менять стили другого элемента?
    Можно ли это сделать только на css?
    К примеру: навожу на блок и хочу чтобы все заголовки в этом блоке стали другого цвета.
    
    Как записать?
    Так не работает:
    
    .block:hover {  .block h1 { color: red;} }
    
        
    

    Ответы

    Ответ 1

    .section { background: #ccc; } .layer { background: #ddd; } .section:hover img { border: 2px solid #333; } .section:hover .layer { border: 2px solid #F90; }

    Lorem Ipsum

    Источник.

    Ответ 2

    Для соседних элементов: .block1:hover + .block2 h1 { color: red;} Для любых элементов(оба блока должны быть внутри одного элемента): .block1:hover ~ .block2 h1 { color: red;}

    нет

    Проведите надо мной

    да


    да

    нет

    нет

    Ответ 3

    .block:hover h1{ color: blue; }

    zagolovok

    zagolovok

    Ответ 4

    .s:hover~.d { color: red; }

    wow

    hey

    Ответ 5

    Если нужно изменить все заголовки в одном блоке, на который навели курсор мыши, то вот так: .main:hover h2 { color: red; }

    How are you?

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente.

    Hi

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente.

    Ok

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente.

    So-so

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente.

    Если же нужно изменять стиль элемента, который находится выше элемента с псевдоклассо :hover, то я делал так (размещал изменяемый элемент ниже элемента с псевдоклассом :hover и при помощи flexbox вытягивал его на нужное мне место): .main { display: flex; flex-direction: column; font: 10px Arial, sans-serif; color: #333; } .one { order: -1; } .two:hover ~ .one { color: red; }

    How are you?

    Hi

    Ok

    So-so

    Ответ 6

    Заранее говорю, русский язык у меня не самая сильная сторона, заранее извиняюсь з ошибки, если будут ;) Выше показанные примеры все правильные, но они очень ограничены при желании изменить другой элемент(который может быть совсем далеко) будет не возможно что-то изменить. Но я могу предложить вариант с JavaScript и он чень простой для усвоения. Главное не бойтесь использовать :) function changeItem() { document.getElementById('one-two').style.width = '200px'; }// функция, которая сработает при наведении. //она означает - выбрать элемент к Id у которого надо что-то изменить. // когда в скобки где написано one-two добавите Id своего элемента function rechangeItem() { document.getElementById('one-two').style.width = '100px'; }// тут всё также. но наобарот. протсес происходящий про отводе курсора. #one, #two, #one-two { width: 100px; height: 30px; background: red; margin: 30px; } /*Надеюсь, что тут все понятно, заданы елементарные свойства :)*/

    Ответ 7

    div { padding:20px; background:#eee; border:1px solid #ccc; margin:10px; } .anotherdiv{ visibility:hidden; opacity:0; transition:all 1s; } .div:hover + .anotherdiv{ visibility:visible; opacity:1; }

    Contrary to popular belief, Lorem Ipsum is not simply rando text. It has roots in a piece of classical Latin literature from 45 BC, making it ove 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for thos interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

    Ответ 8

    По сути, ответа на поставленый вопрос нет пока. "Как при наведении на один элемент (hover) менять стили другого элемента css?" Видимо если элементы не соседние и не дочерние, то только скриптами.

    Ответ 9

    Здесь по классическому CSS за меня всё уже сказали, однако добавлю, что если Вы хотите писать так, как указали (цитирую): .block:hover { .block h1 { color: red;} } Можете использовать препроцессоры CSS (SASS/LESS). Это так скажем усовершенствованный CSS, в котором помимо внутренних блоков можн также использовать усовершенствованные переменные, вычисления и т.д.. Такие файлы компилируютс препроцессором в оригинальный CSS, и к тому же сжимаются (минифицируются, убираются переносы и лишние пробелы, размер файла становится меньше). Достаточно интересная область, достойная внимания.

    Понравилась статья? Поделить с друзьями:
  • Css как изменить цвет рамки input
  • Css как изменить цвет пнг
  • Css как изменить размер border
  • Css как изменить полосу прокрутки css
  • Css как изменить направление текста