Css hover несколько элементов

CSS for hover that includes all child elements

I have a draggable div element with a hover style. This works fine, but the div contains some form elements (label, input). The problem is that when the mouse is over these child elements the hover is disabled.

4 Answers 4

like with all css rules you might have to use .app_setting *:hover < cursor:move !important; >to override any cursor you may have set on child elements elsewhere in you css rules

Using Firefox, (admittedly some years later) this does not work. It actually works even less effectively than the questioners original attempt (using !important or not)

At least 2 ways of doing it:

  • hover states for each child, either explicitly or with * selector, as suggested by garrow .class *:hover
  • cascade hover state to children .class:hover *

There are probably others

This isn’t a css answer, but it might still be useful to you.

Someone else already suggested that you might have to resort to javascript for browser compatibility. If you do resort to javascript, you can use the jquery library to make it easy.

This sets an event handler for hovering into and out of the selected element(s) as matched by the css style selector in the $() call.

Читайте также:  Python reading excel sheet

You might have to resort to JS to make it happen for IE6.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.17.43537

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Css hover несколько элементов

Last updated: Apr 27, 2023
Reading time · 4 min

banner

# Table of Contents

# How to Apply a CSS Hover effect to multiple Elements

To apply a CSS hover effect to multiple elements:

  1. Wrap the elements in div tag.
  2. Apply the hover effect to the div and scope the specific styles to each element.
Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> style> .container:hover .first background-color: aquamarine; > .container:hover .second background-color: lime; > style> head> body> div class="container"> div class="first">First Boxdiv> div class="second">Second boxdiv> div> body> html>

Every time I hover over the div that has a class of container , the hover effects are applied to the div elements with classes of first and second .

Notice that I wrapped the two elements in a wrapper div.

Copied!
div class="container"> div class="first">First Boxdiv> div class="second">Second boxdiv> div>

Both CSS selects are applied when the user hovers over the div that has a class of container .

Copied!
.container:hover .first background-color: aquamarine; > .container:hover .second background-color: lime; >

The example assumes that you want to set different styles on the two elements.

The div element with a class of container doesn’t have to be a direct parent of the other two div tags.

For example, the following code sample also works.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> style> .container:hover .first background-color: aquamarine; > .container:hover .second background-color: lime; > style> head> body> div class="container"> div> div> div class="first">First Boxdiv> div class="second">Second boxdiv> div> div> div> body> html>

# Applying the same hover style to multiple elements

If you need to apply the same hover effect to multiple elements when another element is hovered, separate the selectors by a comma.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> style> .container:hover .first, .container:hover .second background-color: aquamarine; > style> head> body> div class="container"> div class="first">First Boxdiv> div class="second">Second boxdiv> div> body> html>

The example sets the same hover style on both div elements ( first and second ).

Copied!
.container:hover .first, .container:hover .second background-color: aquamarine; >

You can specify as many comma-separated selectors as necessary.

Both elements to which we want to apply the hover effect are divs, so we could simplify the selector a bit.

Copied!
.container:hover div background-color: aquamarine; >

The selector assumes that you want to apply the hover effect to all div elements that are descendants of the container div.

# Apply a CSS hover effect to multiple elements using JavaScript

You can also use JavaScript to apply a CSS hover effect to multiple elements.

  1. Wrap the elements in a div .
  2. Add a mouseover event listener to the wrapper div.
  3. Style the elements in the mouseover event.
  4. Unstyle the elements in a mouseout event.
Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> div class="container"> div class="first">First Boxdiv> div class="second">Second boxdiv> div> script src="index.js"> script> body> html>

Here is the related JavaScript code.

Copied!
const container = document.querySelector('.container'); const first = document.querySelector('.first'); const second = document.querySelector('.second'); container.addEventListener('mouseover', () => first.style.backgroundColor = 'lime'; second.style.backgroundColor = 'aquamarine'; >); container.addEventListener('mouseout', () => first.style.backgroundColor = ''; second.style.backgroundColor = ''; >);

We first selected the elements using the document.querySelector method.

Copied!
const container = document.querySelector('.container'); const first = document.querySelector('.first'); const second = document.querySelector('.second');

The querySelector method takes a selector as a parameter and returns the first matching element.

When selecting an element by a class, you would use the .my-class selector and when selecting an element by id, you would use the #my-id selector.

The next step is to set an event listener that listens for the mouseover event.

Copied!
container.addEventListener('mouseover', () => first.style.backgroundColor = 'lime'; second.style.backgroundColor = 'aquamarine'; >);

The mouseover event gets triggered when the user’s pointing device (a mouse or a trackpad) is used to move the cursor onto the element or one of its children.

When the user hovers over the wrapper div , we apply the hover styles.

Conversely, when the user moves their cursor out of the wrapper div , the mouseout event is triggered.

Copied!
container.addEventListener('mouseout', () => first.style.backgroundColor = ''; second.style.backgroundColor = ''; >);

You can remove the hover styles in the mouseout event.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • Change Select Option Background-Color on Hover in CSS/HTML
  • Check if Element is Input or Select dropdown in JavaScript
  • Change a Button’s color onClick using JavaScript
  • Change button text on Click using JavaScript
  • How to Change Text color on Mouseover in JavaScript
  • How to adjust a Button’s width to fit the Text in CSS
  • How to set a Max Character length in CSS
  • Changing Bold Text into Normal (Unbold Text) in HTML
  • How to bring an element to the Front using CSS
  • Apply multiple inline CSS styles to an HTML element
  • Force the text in a Div to stay in one Line in HTML & CSS
  • justify-self not working in Flexbox issue [Solved]
  • focus() not working in JavaScript issue [Solved]
  • Tailwind CSS classes not working in Vanilla or React project
  • Tailwind CSS extending colors not working [Solutions]
  • Remove whitespace between inline-block elements using CSS

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Hover on element and highlight all elements with the same class

I have many elements with the same class on a web page. I would like to highlight all these elements when I hover one of them. How can I do that in CSS? Right now, I have this CSS:

 

Karen…

Karen ne se retourne pas. Mme Tilford reste là, apparemment confuse et abattue.

CSS is mainly a parent -> child relationship. There are sibling selectors (css-tricks.com/child-and-sibling-selectors) but this will only work if the elements are at the same level, we need to see your setup.

The nested paragraph tags cannot trigger each other with just CSS in that setup. That would require javascript.

I found a solution using JavaScript. See my answer to this similar question: stackoverflow.com/a/15960552/975097

2 Answers 2

The best you can do using pure CSS is this:

.classname:hover ~ .classname

But this only highlights all siblings with a class classname after the hovered element.

You have to use JavaScript to highlight all elements;

var elms = document.getElementsByClassName("classname"); var n = elms.length; function changeColor(color) < for(var i = 0; i < n; i ++) < elms[i].style.backgroundColor = color; >> for(var i = 0; i < n; i ++) < elms[i].onmouseover = function() < changeColor("yellow"); >; elms[i].onmouseout = function() < changeColor("white"); >; > 

If you have multiple classes and want to generalize this, use something like this:

var classes = ["one", "two", "three"]; //list of your classes var elms = <>; var n = <>, nclasses = classes.length; function changeColor(classname, color) < var curN = n[classname]; for(var i = 0; i < curN; i ++) < elms[classname][i].style.backgroundColor = color; >> for(var k = 0; k < nclasses; k ++) < var curClass = classes[k]; elms[curClass] = document.getElementsByClassName(curClass); n[curClass] = elms[curClass].length; var curN = n[curClass]; for(var i = 0; i < curN; i ++) < elms[curClass][i].onmouseover = function() < changeColor(this.className, "yellow"); >; elms[curClass][i].onmouseout = function() < changeColor(this.className, "white"); >; > >; 

Источник

:hover в CSS для двух объектов без общего родителя

Какой правильный синтаксисом псевдо-функции :hover через обращение одного блока к другому, которые находятся не в одном месте? Вот мой код (выдержка из таблицы). Здесь заданы несколько ячеек. введите сюда описание изображения Мне нужно чтоб при наведении курсора на ячейку таблицы (в данном случае класса «y1») появлялся блок из другой ячейки этой же таблицы «mny». Ниже запись самого ховера (которая вероятнее всего неправильная [ну раз она не работает]). введите сюда описание изображения Пролистав 5 электронных учебников и посмотрев 3 видео-ролика на ютубе я всё равно не нашел решение своей проблемы. Единственное важное что видел на одном из сайтов, так это то, что нужно прописывать родительские элементы если объекты не находятся в одном месте. Но как именно это делать (по каким правилам здесь синтаксис) я так и не нашел. Нужно сделать на чистом HTML+CSS (если это вообще возможно) Так же прилаживаю полный HTML и CSS код

/* в сниппете оно не нужно (CbIPoK2513) table< position: absolute; top: 150px; left: 500px; /* border: 2px solid #7FC7FF; */ >*/ td < border: none; >.yach < height: 50px; width: 50px; background-color: #7FC7FF; >.plx < position: relative; /* top: 411px; left: 525px; */ >.ply < position: relative; /* top: 185px; left: 751px; */ >.pl < height: 50px; width: 50px; color: white; font-size: 24px; font-weight: bold; text-decoration: none; background-color: orange; >.txt < position: relative; top: 13.5px; text-align: center; height: 50px; width: 50px; margin: 0px; >.pl:hover < cursor: pointer; opacity: 0.5; transition: 1s; >.mn < position: relative; /* top: 185px; left: 525px; */ height: 50px; width: 50px; color: white; font-size: 24px; font-weight: bold; text-decoration: none; background-color: #8B0000; visibility: hidden; >/* .mnx < position:absolute; top: 126px; left: 525px; >*/ /* .mny < position:absolute; top: 185px; left: 465px; display: none; >*/ .mn:hover < cursor: pointer; opacity: 0.5; transition: 1s; >.x1:hover+.mnx < visibility: visible; >.x2:hover+.mnx < visibility: visible; >.x3:hover+.mnx < visibility: visible; >.x4:hover+.mnx < visibility: visible; >.y1:hover+.mny < visibility: visible; cursor: pointer; >.y2:hover+.mny < visibility: visible; >.y3:hover+.mny < visibility: visible; >.y4:hover+.mny

И так же на всякий случай прилаживаю пример обычного :hover’а двух блоков из-за которого я и хочу сделать полную CSS-анимацию без использования JS

Источник

Оцените статью