Css появляется элемент при наведении

CSS On hover show another element

I want to use CSS to show div when I hover over div , but I cannot figure out how to do it because the div ‘a’ is inside another div that div ‘b’ is not in.

no can do unless you 1) change your markup to have a nested/parent/ancestor relationship, 2) use javscript/jquery

@Jawad Borrowed that from another user’s profile. Felt it was appropriate and necessary in today’s world. =>

As we can know from the answers form this question, parent selector is not supported by all browsers(Firefox). I think a workaround is using JS.

5 Answers 5

we just can show same label div on hovering like this

Precision : it also works if #b is not DIRECTLY after #content. This allows swapping. I’m baffled at how CSS can sometimes eliminate the need of JQuery/Javascript for basic interactions.

@Sajad with the noted HTML and only using CSS, it will never because the sibling selectors cannot go backward hrough HTML, only forward. You’d need to put the #content before #b2 , or use JavaScript, of use the :hover of an element earlier or higher up the DOM.

It is indeed possible with the following code

Now by hovering on element #a shows element #b.

You can use axe selectors for this.

1. Immediate Parent axe Selector ( < )

This axe style rule will select #b , which is the immediate sibling of #content , which is the immediate parent of #a which has a :hover state.

div < display: inline-block; margin: 30px; font-weight: bold; >#content < width: 160px; height: 160px; background-color: rgb(255, 0, 0); >#a, #b < width: 100px; height: 100px; line-height: 100px; text-align: center; >#a < color: rgb(255, 0, 0); background-color: rgb(255, 255, 0); cursor: pointer; >#b < display: none; color: rgb(255, 255, 255); background-color: rgb(0, 0, 255); >#a:hover

2. Remote Element axe Selector ( \ )

This axe style rule will select #b , which is present in the same document as #a which has a :hover state.

div < display: inline-block; margin: 30px; font-weight: bold; >#content < width: 160px; height: 160px; background-color: rgb(255, 0, 0); >#a, #b < width: 100px; height: 100px; line-height: 100px; text-align: center; >#a < color: rgb(255, 0, 0); background-color: rgb(255, 255, 0); cursor: pointer; >#b < display: none; color: rgb(255, 255, 255); background-color: rgb(0, 0, 255); >#a:hover \ #b

github.com/RouninMedia/axe is that what this is? This isn’t officially supported, but it’s your project

This is the right answer because it shows the element only when #b is hovered, and not #content alone.

Great work you’ve got @Rounin. Your library greatly helped. I will study it more. I will also love to be a part of the continued success. If there’s any way i can help; kindly let me know.

Читайте также:  Python encode non ascii characters

You’re very kind, @Olamigoke Philip. It’s currently about 33% finished (and, honestly, I’ve not really worked on it since Jan-Feb 2017). If all goes well, I plan to move axe forward in 2021. Not least I want to significantly advance the axeBlades extension.

Источник

Как при наведении на что-либо заставить появится блок?

@goodalien1125, в данном случае — нужно, просто помещать весь контент в ссылку — это семантически глупо. Поэтому используем селектор отбора соседа (можно и + , но тут особо не так уж важно).

Вот так тоже можно — мои 5 копеек

* < margin:0; padding:0; >.first < width:300px; height:50px; background:yellow; margin:20px auto; position:relative; border-radius:6px; line-height:50px; >.first:hover < border-radius:6px 6px 0 0; >.first>p < padding-left:20px; text-transform:uppercase; text-decoration:underline; color:blue; cursor:pointer; >.first .parent < position:absolute; top:20px; left:0; width:300px; height:0; line-height:1px; border-left:2px solid yellow; border-right:2px solid yellow; border-bottom:2px solid yellow; box-sizing:border-box; border-radius:0 0 10px 10px; transition-duration:1s; transition-delay:1s; padding:10px; >.first .parent img < display:block; width:0; height:0; transition:all 1s; transition-duration:1s; transition-delay:1s; >.first:hover .parent img < float:left; width:45%; height:auto; margin-top:5px; margin-left:5px; margin-bottom:-5px; >.first .parent p < display:block; width:90%; margin:10px 5px; text-align:justify; font-size:0; transition-duration:1s; transition-delay:1s; color:#fff; >.first:hover .parent < position:absolute; top:50px; left:0; width:300px; min-height:390px; line-height:16px; border-left:2px solid yellow; border-right:2px solid yellow; border-bottom:2px solid yellow; box-sizing:border-box; border-radius:0 0 6px 6px; >.first:hover .parent p
  

Наведи на меня

image

Lorem Ipsum - это текст-"рыба", часто используемый в печати и вэб-дизайне. Lorem Ipsum является стандартной "рыбой" для текстов на латинице с начала XVI века. В то время некий безымянный печатник создал большую коллекцию размеров и форм шрифтов, используя Lorem Ipsum для распечатки образцов.

Lorem Ipsum не только успешно пережил без заметных изменений пять веков, но и перешагнул в электронный дизайн. Его популяризации в новое время послужили публикация листов Letraset с образцами Lorem Ipsum в 60-х годах и, в более недавнее время, программы электронной вёрстки типа Aldus PageMaker, в шаблонах которых используется Lorem Ipsum.

Источник

Using only CSS, show div on hover over another element

@Pawel Bulwan I combined the «:hover» with «+» CSS selector suggestions from here with a :target suggestion for showing content on click (from stackoverflow.com/questions/18849520/…) into a solution that should work with both mouse and touch — zoomicon.wordpress.com/2017/11/25/…

following up on my last comment, also see some useful variations at a comment reply I did on that blog post: zoomicon.wordpress.com/2017/11/25/…

14 Answers 14

You can do something like this:

HTML5 allows anchor elements to wrap almost anything, so in that case the div element can be made a child of the anchor. Otherwise the principle is the same — use the :hover pseudo-class to change the display property of another element.

This will make every

on the page display:none and when the mouse hovers over «Hover over me!» it will make every
following the inside the same parent display:block . It might be a better idea to select by .class-name or by #id . Otherwise, good post.

It might be prudent to use visibility instead of display. As I recall, it’s more efficient because display redraws the div every time. Although it probably doesn’t matter for one div, if you have to do many, it might be better to make them invisible instead.

.showme < display: none; >.showhim:hover .showme

Since this answer is popular I think a small explanation is needed. Using this method when you hover on the internal element, it wont disappear. Because the .showme is inside .showhim it will not disappear when you move your mouse between the two lines of text (or whatever it is).

Читайте также:  Paging in php with ajax

These are example of quirqs you need to take care of when implementing such behavior.

It all depends what you need this for. This method is better for a menu style scenario, while Yi Jiang’s is better for tooltips.

i know its better, thats why i upvoted it 🙂 i gave a working example, presenting a concept (css selectors more specifically), dont see why downvote it ^^

I found using opacity is better, it allows you to add css3 transitions to make a nice finished hover effect. The transitions will just be dropped by older IE browsers, so it degrades gracefully to.

#stuff < opacity: 0.0; -webkit-transition: all 500ms ease-in-out; -moz-transition: all 500ms ease-in-out; -ms-transition: all 500ms ease-in-out; -o-transition: all 500ms ease-in-out; transition: all 500ms ease-in-out; >#hover < width:80px; height:20px; background-color:green; margin-bottom:15px; >#hover:hover + #stuff

This is great, I used this for a much larger div. I wanted the «stuff» div to remain visible if I moved my cursor from the «hover» div to the «stuff» div so I changed the last style element from #hover:hover + #stuff < to #hover:hover + #stuff, #stuff:hover < . Then the "stuff" div remains visible when you move over that div!

I’m by no means an expert, but I’m incredibly proud of myself for having worked something out about this code. If you do:

Note the > , a direct child selector.

You can contain the whole thing in an a tag, then, as long as your trigger (which can be in it’s own div, or straight up in the a tag, or anything you want) is physically touching the revealed div, you can move your mouse from one to the other.

Maybe this isn’t useful for a great deal, but I had to set my revealed div to overflow: auto, so sometimes it had scroll bars, which couldn’t be used as soon as you move away from the div.

In fact, after finally working out how to make the revealed div, (although it is now a child of the trigger, not a sibling), sit behind the trigger, in terms of z-index, (with a little help from this page: How to get a parent element to appear above child) you don’t even have to roll over the revealed div to scroll it, just stay hovering over the trigger and use your wheel, or whatever.

My revealed div covers most of the page, so this technique makes it a lot more permanent, rather than the screen flashing from one state to another with every move of the mouse. It’s really intuitive actually, hence why I’m really quite proud of myself.

Читайте также:  Java load file name

The only downside is that you can’t put links within the whole thing, but you can use the whole thing as one big link.

Источник

Появление блока при наведении с помощью CSS

Приклад

Доброго времени суток. 🙂
Сегодня хочу показать Вам два способа как можно организовать появление блока при наведении на другой блок, используя только CSS.

Пример

no image

Первый способ, когда блок появляется как-бы поверх основного блока, но не выходя за его границы. Данный способ мне пригодился при создании темы для онлайн кинотеатра, а именно для организации появления знака play при наведении на постер фильма.

Второй способ по сути такой же, но в нем второй блок появляется в виде выноски.
И так приступим.

Способ номер один

Данный способ очень простенький и его суть заключается в следующем.

1. HTML разметка

Тут все просто, нужно внутри одного div-а разместить второй как в примере ниже

2. Стили CSS

Тут тоже нет ничего сложного, просто прописываем стили для блоков. Для первого задаем размеры и position:relative
для второго position:absolute и позиционирование left, bottom, right, top, также свойство display:none.

.holder < position:relative; width:300px; height:400px; background:#ff6600; margin:100px auto; >.block < position:absolute; left:0; bottom:0; right:0; top:0; background:rgba(255,255,255, 0.7); padding:5px; display:none; >.holder:hover .block

Способ номер два

Данный способ по сути — то же самое, но с некоторым изменением стилей. Для удобства я поменял название классов, чтобы не запутаться.

1. HTML разметка

2. Стили CSS

.poster < position:relative; margin:100px auto; background:#ff6600; height:200px; width:150px; >.descr < display:none; margin-left:-350px; padding:10px; margin-top:17px; background:#f3f3f3; height:200px; -moz-box-shadow:0 5px 5px rgba(0,0,0,0.3); -webkit-box-shadow:0 5px 5px rgba(0,0,0,0.3); box-shadow:0 5px 5px rgba(0,0,0,0.3); >.poster:hover .descr

Пример

Можете все подогнать под свои нужды и если все сделали правильно, то у вас должно получится как в примере.

На этом Все, спасибо за внимание 🙂

Якщо Вам була корисна моя праця, можете фінансово підтримати сайт або відключити блокувальник реклами, що займе 2 хвилини 🙂

Заказ обратного звонка

Доброго вам дня. На всіх своїх темах, які я роблю для замовників я встановлюю свої кнопки шаринга в соціальних мережах. Вони мають різну кількість кнопок, але найчастіше я використовую стандартний…

Доброго времени суток На всех своих темах, которые я делаю для заказчиков я устанавливаю свои кнопки шаринга в социальных сетях. Они имеют разное количество кнопок, но чаще всего я использую…

Доброго вам дня. Сьогодні буде простенька стаття про те, як зробити просте виїжджаюче меню без використання скриптів, тобто на чистому html + CSS. Даний урок буде корисний тим, хто верстає…

Доброго времени суток Сегодня будет простенькая статья о том как сделать простое выезжающее меню без использования скриптов, то есть на чистом html + CSS. Данный урок будет полезен тем, кто…

ссылки на Viber, Whatsapp, Telegram, Skype

Якорные ссылки

Появление блока при наведении с помощью CSS

wp-cron.php и нагрузка на сайт, что делать?

индекс Google

Как вывести все записи и разбить их по рубриками WordPress

© 2013 — 2023 гг. Gnatkovsky.com.ua — Дизайн і розробка сайтів. Всі права захищені. Будь-яке використання матеріалів допускається лише з зазначенням активного посилання на джерело. Повне копіювання інформації, крадіжка контенту — ЗАБОРОНЕНО. У разі виявлення сайту використовує повністю скопійований матеріал, будуть вжиті заходи.

Источник

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