I’m trying to make a div’s background color change on mouse over.
the div {background:white;}
the div a:hover{background:grey; width:100%;
display:block; text-decoration:none;}
only the link inside the div gets the background color.
what could I do to make the whole div get that background color?
thank you
EDIT :
how can I make the whole div to act as a link — when you click anywhere on that div, to take you to an address.
1
The «a:hover
» literally tells the browser to change the properties for the <a>
-tag, when the mouse is hovered over it. What you perhaps meant was «the div:hover
» instead, which would trigger when the div was chosen.
Just to make sure, if you want to change only one particular div, give it an id («<div id='something'>
«) and use the CSS «#something:hover {...}
» instead. If you want to edit a group of divs, make them into a class («<div class='else'>
«) and use the CSS «.else {...}
» in this case (note the period before the class’ name!)
0
Using Javascript
<div id="mydiv" style="width:200px;background:white" onmouseover="this.style.background='gray';" onmouseout="this.style.background='white';">
Jack and Jill went up the hill To fetch a pail of water. Jack fell down and broke his crown, And Jill came tumbling after.
</div>
0
There is no need to put anchor. To change style of div on hover then
Change background color of div on hover.
.div_hover {
background-color: #FFFFFF;
}
.div_hover:hover {
background-color: #000000;
}
<div class="div_hover"> Change div background color on hover</div>
To make the whole div act as a link, set the anchor tag as:
display: block
And set your height of the anchor tag to 100%.
Then set a fixed height to your div tag.
Then style your anchor tag like usual.
For example:
<html>
<head>
<title>DIV Link</title>
<style type="text/css">
.link-container {
border: 1px solid;
width: 50%;
height: 20px;
}
.link-container a {
display: block;
background: #c8c8c8;
height: 100%;
text-align: center;
}
.link-container a:hover {
background: #f8f8f8;
}
</style>
</head>
<body>
<div class="link-container">
<a href="http://www.stackoverflow.com">Stack Overflow</a>
</div>
<div class="link-container">
<a href="http://www.stackoverflow.com">Stack Overflow</a>
</div>
</body> </html>
Good luck!
0
html code:
<!DOCTYPE html>
<html>
<head><title>this is your web page</title></head>
<body>
<div class = "nicecolor"></div>
</body>
</html>
css code:
.nicecolor {
color:red;
width:200px;
height:200px;
}
.nicecolor:hover {
color:blue;
}
and thats how youll change your div from red to blue by hovering over it.
Set
display: block;
on a and give some height
simply try «hover» property of CSS. eg:
<html>
<head>
<style>
div
{
height:100px;
width:100px;
border:2px solid red;
}
div:hover
{
background-color:yellow;
}
</style>
</head>
<body>
<a href="#">
<div id="ab">
<p> hello there </p>
</div>
</a>
</body>
i hope this will help
You can just put the anchor around the div.
<a class="big-link"><div>this is a div</div></a>
and then
a.big-link {
background-color: 888;
}
a.big-link:hover {
background-color: f88;
}
you could just contain the div in anchor tag like this:
a{
text-decoration:none;
color:#ffffff;
}
a div{
width:100px;
height:100px;
background:#ff4500;
}
a div:hover{
background:#0078d7;
}
<body>
<a href="http://example.com">
<div>
Hover me
</div>
</a>
</body>
Just make the property !important
in your css file so that background color doesnot change on mouse over.This worked for me.
Example:
.fbColor {
background-color: #3b5998 !important;
color: white;
}
1
I need to change the background color of an image. The image is a circle image with white background, I need when you hover over it change the background of the circle image to blue. I need only the circle to be change.
My HTML code is
<div class="fb-icon">
<a href="http://www.facebook.com/mypage" target="_blank">
<img src="images/fb_normal.png" alt="Facebook">
</a>
</div>
In CSS I wrote:
.fb-icon:hover {
background: blue;
}
The above code gives me blue color but as a frame around the circle icon. what I need is to change the background of the circle itself. Imagine it’s like a signal it’s white when you hover by mouse it goes to blue.
Please I need a solution if it can be done by CSS or whatever. Sorry if I make it too long.
The problem: link
asked Jan 28, 2012 at 17:09
HTML ManHTML Man
9254 gold badges17 silver badges39 bronze badges
6
Ideally you should use a transparent PNG with the circle in white and the background of the image transparent. Then you can set the background-color
of the .fb-icon
to blue on hover. So you’re CSS would be:
fb-icon{
background:none;
}
fb-icon:hover{
background:#0000ff;
}
Additionally, if you don’t want to use PNG’s you can also use a sprite and alter the background position. A sprite is one large image with a collection of smaller images which can be used as a background image by changing the background position. So for eg, if your original circle image with the white background is 100px X 100px, you can increase the height of the image to 100px X 200px, so that the top half is the original image with the white background, while the lower half is the new image with the blue background. Then you set setup your CSS as:
fb-icon{
background:url('path/to/image/image.png') no-repeat 0 0;
}
fb-icon:hover{
background:url('path/to/image/image.png') no-repeat 0 -100px;
}
answered Jan 28, 2012 at 17:41
Sagar PatilSagar Patil
1,92812 silver badges21 bronze badges
1
It’s a bit late but I came across this post.
It’s not perfect but here’s what I do.
HTML Code
<div class="showcase-menu-social"><img class="margin-left-20" src="images/graphics/facebook-50x50.png" alt="facebook-50x50" width="50" height="50" /><img class="margin-left-20" src="images/graphics/twitter-50x50.png" alt="twitter-50x50" width="50" height="50" /><img class="margin-left-20" src="images/graphics/youtube-50x50.png" alt="youtube-50x50" width="50" height="50" /></div>
CSS Code
.showcase-menu {
margin-left:20px;
margin-right:20px;
padding: 0px 20px 0px 20px;
background-color: #C37500;
behavior: url(/css/border-radius.htc);
border-radius: 20px;
}
.showcase-menu-social img:hover {
background-color: #C37500;
opacity:0.7 !important;
filter:alpha(opacity=70) !important; /* For IE8 and earlier */
box-shadow: 0 0 0px #000000 !important;
}
Now my border radius of 20px matches up exactly with the image border radius. As you can see the .showcase-menu has the same background as the .showcase-menu-social. What this does is to allow the ‘opacity’ to take effect and no ‘square’ background or border shows, thus the image slightly reduces it’s saturation on hover.
It’s a nice effect and does give the viewer the feedback that the image is in focus. I’m fairly sure on a darker background, it would have even a better effect.
The nice thing is that this is valid HTML-CSS code and will validate. To be honest, it should work on non-image elements just as good as images.
Enjoy!
answered Jul 18, 2013 at 7:00
2
An alternative solution would be to use the new CSS mask image functionality which works in everything apart from IE (still not supported in IE11). This would be more versatile and maintainable than some of the other solutions suggested here. You could also more generally use SVG.
e.g.
item { mask: url('/mask-image.png'); }
There is an example of using a mask image here:
http://codepen.io/zerostyle/pen/tHimv
and lots of examples here:
http://codepen.io/yoksel/full/fsdbu/
answered Aug 15, 2014 at 11:04
WillsterWillster
2,5061 gold badge32 silver badges32 bronze badges
If the icon is from Font Awesome (https://fontawesome.com/icons/)
then you could tap into the color css property to change it’s background.
fb-icon{
color:none;
}
fb-icon:hover{
color:#0000ff;
}
This is irrespective of the color it had. So you could use an entirely different color in its usual state and define another in its active state.
answered May 25, 2020 at 17:14
brytebeebrytebee
411 silver badge7 bronze badges
If I understand correctly then it would be easier if you gave your image a transparent background and set the background container’s background-color property without having to use filters and so on.
http://www.ajaxblender.com/howto-convert-image-to-grayscale-using-javascript.html
Shows you how to use filters in IE. Maybe if you leverage something from that. Not very cross-browser compatible though. Another option might be to have two images and use them as background-images (rather than img tags), swap one out after another using the :hover pseudo selector.
answered Jan 28, 2012 at 17:13
backdeskbackdesk
1,7713 gold badges22 silver badges42 bronze badges
1
Ok, try this:
Get the image with the transparent circle — http://i39.tinypic.com/15s97vd.png
Put that image in a html element and change that element’s background color via css. This way you get the logo with the circle in the color defined in the stylesheet.
The html
<div class="badassColorChangingLogo">
<img src="http://i39.tinypic.com/15s97vd.png" />
Or download the image and change the path to the downloaded image in your machine
</div>
The css
div.badassColorChangingLogo{
background-color:white;
}
div.badassColorChangingLogo:hover{
background-color:blue;
}
Keep in mind that this wont work on non-alpha capable browsers like ie6, and ie7. for ie you can use a js fix. Google ddbelated png fix and you can get the script.
answered Jan 28, 2012 at 18:07
JuankJuank
5,9661 gold badge27 silver badges28 bronze badges
1
Use the background-color property instead of the background property in your CSS.
So your code will look like this:
.fb-icon:hover {
background: blue;
}
answered Sep 28, 2013 at 22:51
Oliver NiOliver Ni
2,5677 gold badges30 silver badges43 bronze badges
The best approach is to use a svg image in which the background would be a white rect and the foreground the circle, and set the hover property to the bg. It’s a vector graphic image so it will look fine on any screen size, not to mention that svg is meant to be used in the web. This svg should be just of some bytes and its rendered better than any raster or bitmap image.
answered Aug 4, 2021 at 0:19
I need to change the background color of an image. The image is a circle image with white background, I need when you hover over it change the background of the circle image to blue. I need only the circle to be change.
My HTML code is
<div class="fb-icon">
<a href="http://www.facebook.com/mypage" target="_blank">
<img src="images/fb_normal.png" alt="Facebook">
</a>
</div>
In CSS I wrote:
.fb-icon:hover {
background: blue;
}
The above code gives me blue color but as a frame around the circle icon. what I need is to change the background of the circle itself. Imagine it’s like a signal it’s white when you hover by mouse it goes to blue.
Please I need a solution if it can be done by CSS or whatever. Sorry if I make it too long.
The problem: link
asked Jan 28, 2012 at 17:09
HTML ManHTML Man
9254 gold badges17 silver badges39 bronze badges
6
Ideally you should use a transparent PNG with the circle in white and the background of the image transparent. Then you can set the background-color
of the .fb-icon
to blue on hover. So you’re CSS would be:
fb-icon{
background:none;
}
fb-icon:hover{
background:#0000ff;
}
Additionally, if you don’t want to use PNG’s you can also use a sprite and alter the background position. A sprite is one large image with a collection of smaller images which can be used as a background image by changing the background position. So for eg, if your original circle image with the white background is 100px X 100px, you can increase the height of the image to 100px X 200px, so that the top half is the original image with the white background, while the lower half is the new image with the blue background. Then you set setup your CSS as:
fb-icon{
background:url('path/to/image/image.png') no-repeat 0 0;
}
fb-icon:hover{
background:url('path/to/image/image.png') no-repeat 0 -100px;
}
answered Jan 28, 2012 at 17:41
Sagar PatilSagar Patil
1,92812 silver badges21 bronze badges
1
It’s a bit late but I came across this post.
It’s not perfect but here’s what I do.
HTML Code
<div class="showcase-menu-social"><img class="margin-left-20" src="images/graphics/facebook-50x50.png" alt="facebook-50x50" width="50" height="50" /><img class="margin-left-20" src="images/graphics/twitter-50x50.png" alt="twitter-50x50" width="50" height="50" /><img class="margin-left-20" src="images/graphics/youtube-50x50.png" alt="youtube-50x50" width="50" height="50" /></div>
CSS Code
.showcase-menu {
margin-left:20px;
margin-right:20px;
padding: 0px 20px 0px 20px;
background-color: #C37500;
behavior: url(/css/border-radius.htc);
border-radius: 20px;
}
.showcase-menu-social img:hover {
background-color: #C37500;
opacity:0.7 !important;
filter:alpha(opacity=70) !important; /* For IE8 and earlier */
box-shadow: 0 0 0px #000000 !important;
}
Now my border radius of 20px matches up exactly with the image border radius. As you can see the .showcase-menu has the same background as the .showcase-menu-social. What this does is to allow the ‘opacity’ to take effect and no ‘square’ background or border shows, thus the image slightly reduces it’s saturation on hover.
It’s a nice effect and does give the viewer the feedback that the image is in focus. I’m fairly sure on a darker background, it would have even a better effect.
The nice thing is that this is valid HTML-CSS code and will validate. To be honest, it should work on non-image elements just as good as images.
Enjoy!
answered Jul 18, 2013 at 7:00
2
An alternative solution would be to use the new CSS mask image functionality which works in everything apart from IE (still not supported in IE11). This would be more versatile and maintainable than some of the other solutions suggested here. You could also more generally use SVG.
e.g.
item { mask: url('/mask-image.png'); }
There is an example of using a mask image here:
http://codepen.io/zerostyle/pen/tHimv
and lots of examples here:
http://codepen.io/yoksel/full/fsdbu/
answered Aug 15, 2014 at 11:04
WillsterWillster
2,5061 gold badge32 silver badges32 bronze badges
If the icon is from Font Awesome (https://fontawesome.com/icons/)
then you could tap into the color css property to change it’s background.
fb-icon{
color:none;
}
fb-icon:hover{
color:#0000ff;
}
This is irrespective of the color it had. So you could use an entirely different color in its usual state and define another in its active state.
answered May 25, 2020 at 17:14
brytebeebrytebee
411 silver badge7 bronze badges
If I understand correctly then it would be easier if you gave your image a transparent background and set the background container’s background-color property without having to use filters and so on.
http://www.ajaxblender.com/howto-convert-image-to-grayscale-using-javascript.html
Shows you how to use filters in IE. Maybe if you leverage something from that. Not very cross-browser compatible though. Another option might be to have two images and use them as background-images (rather than img tags), swap one out after another using the :hover pseudo selector.
answered Jan 28, 2012 at 17:13
backdeskbackdesk
1,7713 gold badges22 silver badges42 bronze badges
1
Ok, try this:
Get the image with the transparent circle — http://i39.tinypic.com/15s97vd.png
Put that image in a html element and change that element’s background color via css. This way you get the logo with the circle in the color defined in the stylesheet.
The html
<div class="badassColorChangingLogo">
<img src="http://i39.tinypic.com/15s97vd.png" />
Or download the image and change the path to the downloaded image in your machine
</div>
The css
div.badassColorChangingLogo{
background-color:white;
}
div.badassColorChangingLogo:hover{
background-color:blue;
}
Keep in mind that this wont work on non-alpha capable browsers like ie6, and ie7. for ie you can use a js fix. Google ddbelated png fix and you can get the script.
answered Jan 28, 2012 at 18:07
JuankJuank
5,9661 gold badge27 silver badges28 bronze badges
1
Use the background-color property instead of the background property in your CSS.
So your code will look like this:
.fb-icon:hover {
background: blue;
}
answered Sep 28, 2013 at 22:51
Oliver NiOliver Ni
2,5677 gold badges30 silver badges43 bronze badges
The best approach is to use a svg image in which the background would be a white rect and the foreground the circle, and set the hover property to the bg. It’s a vector graphic image so it will look fine on any screen size, not to mention that svg is meant to be used in the web. This svg should be just of some bytes and its rendered better than any raster or bitmap image.
answered Aug 4, 2021 at 0:19
В данной статье на примере показано, как сделать на произвольном элементе сайта смену цвета, если на него был наведен курсор мышки.
Делается данная «штука» при помощи стилей CSS, т.е. придется добавить несколько строчек текста в файл стилей шаблона, а так же проявить свои дизайнерские способности. Я подскажу что именно добавить.
Обновлено 17.01.2019
Давайте сразу для наглядности пример, чтобы поняли о чем речь. Проведите мышкой по пунктам меню:
Как только мышка оказывается наведена на любое поле в списке — происходит смена заднего фона строки, а так же цвет текста/ссылки в названии рубрики сайта.
Вот так выглядит код данного блока:
В моем примере видим что эффект срабатывает на обычной ссылке. Вместо нее может быть контейнер <div>
, <li>
и прочие подходящие теги.
Чтобы сказать браузеру, что эффект нужно выполнять на конкретных ссылках, я взял их в отдельный <div class="catside">тут ссылки<div>
. У вас это тоже может быть созданный вами контейнер, или уже готовый (например, виджет в сайдбаре).
Практика
Теперь необходимо задать действие по наведению мышки. Как уже говорилось выше — делаем все при помощи стилей CSS (файл шаблона может называться style.css, css.css, core.css или еще как-то).
.catside a:hover { background: #0078BF; color: #fff; }
Данной строкой мы указали браузеру менять цвет заднего фона при наведении мышки на синий (#0078BF) и сказали что цвет шрифта должен стать белым (#fff). Сама «штука», позволяющая понять браузеру, что это нужно делать по наведению мышки — псевдокласс hover (о нем можно почитать ЗДЕСЬ).
Чуть понятнее: мы указали что ссылка a
должна находиться внутри контейнера с классом .catside
. Далее мы добавили псевдокласс hover и оформили по правилам CSS.
Послесловие
В данной статье я показал как работает смена цвета элементов на самом обычном примере. Если хотите развиваться далее, то почитайте профильную литературу и справочники по CSS.
Использовать hover можно, практически, для всех элементов на сайте: блоки, текст, ссылки. Проявите немного фантазии и поймете как устроено у вас на сайте подобное. После этого сможете его украсить или сменить частично оформление.
Опять же о показанном примере: в нем не учитываются параметры оформления блока (отступы, размер шрифта, картинка и прочее). Это все можно узнать из моих предыдущих статей на блоге, либо воспользоваться консолью разработчика F12 в вашем браузере (как им пользоваться смотрите видео на моем канале YOUTUBE).
I’m trying to make a div’s background color change on mouse over.
the div {background:white;}
the div a:hover{background:grey; width:100%;
display:block; text-decoration:none;}
only the link inside the div gets the background color.
what could I do to make the whole div get that background color?
thank you
EDIT :
how can I make the whole div to act as a link — when you click anywhere on that div, to take you to an address.
1
The «a:hover
» literally tells the browser to change the properties for the <a>
-tag, when the mouse is hovered over it. What you perhaps meant was «the div:hover
» instead, which would trigger when the div was chosen.
Just to make sure, if you want to change only one particular div, give it an id («<div id='something'>
«) and use the CSS «#something:hover {...}
» instead. If you want to edit a group of divs, make them into a class («<div class='else'>
«) and use the CSS «.else {...}
» in this case (note the period before the class’ name!)
0
Using Javascript
<div id="mydiv" style="width:200px;background:white" onmouseover="this.style.background='gray';" onmouseout="this.style.background='white';">
Jack and Jill went up the hill To fetch a pail of water. Jack fell down and broke his crown, And Jill came tumbling after.
</div>
0
There is no need to put anchor. To change style of div on hover then
Change background color of div on hover.
.div_hover {
background-color: #FFFFFF;
}
.div_hover:hover {
background-color: #000000;
}
<div class="div_hover"> Change div background color on hover</div>
To make the whole div act as a link, set the anchor tag as:
display: block
And set your height of the anchor tag to 100%.
Then set a fixed height to your div tag.
Then style your anchor tag like usual.
For example:
<html>
<head>
<title>DIV Link</title>
<style type="text/css">
.link-container {
border: 1px solid;
width: 50%;
height: 20px;
}
.link-container a {
display: block;
background: #c8c8c8;
height: 100%;
text-align: center;
}
.link-container a:hover {
background: #f8f8f8;
}
</style>
</head>
<body>
<div class="link-container">
<a href="http://www.stackoverflow.com">Stack Overflow</a>
</div>
<div class="link-container">
<a href="http://www.stackoverflow.com">Stack Overflow</a>
</div>
</body> </html>
Good luck!
0
html code:
<!DOCTYPE html>
<html>
<head><title>this is your web page</title></head>
<body>
<div class = "nicecolor"></div>
</body>
</html>
css code:
.nicecolor {
color:red;
width:200px;
height:200px;
}
.nicecolor:hover {
color:blue;
}
and thats how youll change your div from red to blue by hovering over it.
Set
display: block;
on a and give some height
simply try «hover» property of CSS. eg:
<html>
<head>
<style>
div
{
height:100px;
width:100px;
border:2px solid red;
}
div:hover
{
background-color:yellow;
}
</style>
</head>
<body>
<a href="#">
<div id="ab">
<p> hello there </p>
</div>
</a>
</body>
i hope this will help
You can just put the anchor around the div.
<a class="big-link"><div>this is a div</div></a>
and then
a.big-link {
background-color: 888;
}
a.big-link:hover {
background-color: f88;
}
you could just contain the div in anchor tag like this:
a{
text-decoration:none;
color:#ffffff;
}
a div{
width:100px;
height:100px;
background:#ff4500;
}
a div:hover{
background:#0078d7;
}
<body>
<a href="http://example.com">
<div>
Hover me
</div>
</a>
</body>
Just make the property !important
in your css file so that background color doesnot change on mouse over.This worked for me.
Example:
.fbColor {
background-color: #3b5998 !important;
color: white;
}
1
I’m trying to make a div’s background color change on mouse over.
the div {background:white;}
the div a:hover{background:grey; width:100%;
display:block; text-decoration:none;}
only the link inside the div gets the background color.
what could I do to make the whole div get that background color?
thank you
EDIT :
how can I make the whole div to act as a link — when you click anywhere on that div, to take you to an address.
1
The «a:hover
» literally tells the browser to change the properties for the <a>
-tag, when the mouse is hovered over it. What you perhaps meant was «the div:hover
» instead, which would trigger when the div was chosen.
Just to make sure, if you want to change only one particular div, give it an id («<div id='something'>
«) and use the CSS «#something:hover {...}
» instead. If you want to edit a group of divs, make them into a class («<div class='else'>
«) and use the CSS «.else {...}
» in this case (note the period before the class’ name!)
0
Using Javascript
<div id="mydiv" style="width:200px;background:white" onmouseover="this.style.background='gray';" onmouseout="this.style.background='white';">
Jack and Jill went up the hill To fetch a pail of water. Jack fell down and broke his crown, And Jill came tumbling after.
</div>
0
There is no need to put anchor. To change style of div on hover then
Change background color of div on hover.
.div_hover {
background-color: #FFFFFF;
}
.div_hover:hover {
background-color: #000000;
}
<div class="div_hover"> Change div background color on hover</div>
To make the whole div act as a link, set the anchor tag as:
display: block
And set your height of the anchor tag to 100%.
Then set a fixed height to your div tag.
Then style your anchor tag like usual.
For example:
<html>
<head>
<title>DIV Link</title>
<style type="text/css">
.link-container {
border: 1px solid;
width: 50%;
height: 20px;
}
.link-container a {
display: block;
background: #c8c8c8;
height: 100%;
text-align: center;
}
.link-container a:hover {
background: #f8f8f8;
}
</style>
</head>
<body>
<div class="link-container">
<a href="http://www.stackoverflow.com">Stack Overflow</a>
</div>
<div class="link-container">
<a href="http://www.stackoverflow.com">Stack Overflow</a>
</div>
</body> </html>
Good luck!
0
html code:
<!DOCTYPE html>
<html>
<head><title>this is your web page</title></head>
<body>
<div class = "nicecolor"></div>
</body>
</html>
css code:
.nicecolor {
color:red;
width:200px;
height:200px;
}
.nicecolor:hover {
color:blue;
}
and thats how youll change your div from red to blue by hovering over it.
Set
display: block;
on a and give some height
simply try «hover» property of CSS. eg:
<html>
<head>
<style>
div
{
height:100px;
width:100px;
border:2px solid red;
}
div:hover
{
background-color:yellow;
}
</style>
</head>
<body>
<a href="#">
<div id="ab">
<p> hello there </p>
</div>
</a>
</body>
i hope this will help
You can just put the anchor around the div.
<a class="big-link"><div>this is a div</div></a>
and then
a.big-link {
background-color: 888;
}
a.big-link:hover {
background-color: f88;
}
you could just contain the div in anchor tag like this:
a{
text-decoration:none;
color:#ffffff;
}
a div{
width:100px;
height:100px;
background:#ff4500;
}
a div:hover{
background:#0078d7;
}
<body>
<a href="http://example.com">
<div>
Hover me
</div>
</a>
</body>
Just make the property !important
in your css file so that background color doesnot change on mouse over.This worked for me.
Example:
.fbColor {
background-color: #3b5998 !important;
color: white;
}
1
Как изменить вид ссылки при наведении на нее курсора мыши?
Internet Explorer | Chrome | Opera | Safari | Firefox | Android | iOS |
4.0+ | 1.0+ | 4.0+ | 1.0+ | 1.0+ |
Задача
Изменить цвет текстовой ссылки, когда на неё наводится курсор мыши и вернуть цвет обратно при уведении курсора.
Решение
Псевдокласс :hover, который добавляется к селектору A, определяет состояние ссылки при наведённом на неё курсоре мыши. В стилях вначале указывается
селектор A, потом :hover (пример 1).
Пример 1. Изменение вида ссылки
HTML5CSS 2.1IECrOpSaFx
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Цвет ссылок</title>
<style>
a {
color: #008000; /* Цвет обычной ссылки */
text-decoration: none; /* Убираем подчеркивание у ссылок */
}
a:visited {
color: #800080; /* Цвет посещённой ссылки */
}
a:hover {
color: #800000; /* Цвет ссылки при наведении на нее курсора мыши */
text-decoration: underline; /* Добавляем подчеркивание */
}
</style>
</head>
<body>
<p><a href="rome.html">Cras ingens iterabimus aequor</a> —
завтра снова мы выйдем в огромное море.</p>
</body>
</html>
В данном примере ссылка становится подчёркнутой и меняет свой цвет, когда
на неё наводится указатель (рис. 1). Заметьте, что псевдокласс :hover в коде
идёт после :visited. Это имеет значение, иначе посещённые ссылки в данном случае
не будут изменять свой цвет.
Рис. 1. Вид ссылки при наведении на неё курсора мыши
Аналогично можно изменить и цвет фона под ссылкой при её наведении, добавив свойство background к селектору A:hover, как показано в примере 2.
Пример 2. Изменение цвета фона ссылки
HTML5CSS 2.1IECrOpSaFx
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Фон под ссылками</title>
<style>
a {
color: #000080; /* Цвет обычной ссылки */
padding: 2px; /* Поля вокруг текста */
}
a:visited {
color: #800080; /* Цвет посещенной ссылки */
}
a:hover {
text-decoration: none; /* Убираем подчеркивание */
color: #fff; /* Цвет ссылки при наведении на нее курсора мыши */
background: #e24486; /* Цвет фона */
}
</style>
</head>
<body>
<p><a href="rome.html">Audaces fortuna juvat</a> -
счастье покровительствует смелым.</p>
</body>
</html>
Результат данного примера показан на рис. 2. Чтобы текст плотно не прилегал к фону, к селектору A добавлено свойство padding.
Рис. 2. Изменение цвета фона ссылки
Псевдокласс :hover
срабатывает, когда пользователь наводит на элемент мышью, но не обязательно активирует его.
Этот стиль может переопределяться другими относящимися к ссылкам псевдоклассами, такими как :link
, :visited
и :active
, появляющимися в соответствующем порядке. Чтобы стилизировать ссылки должным образом, вам нужно вставлять правило :hover
до правил :link
и :visited
, но после :active
, как определено в LVHA-порядке: :link
— :visited
— :hover
— :active
.
Псевдокласс :hover
может применяться к любому псевдоэлементу.
Браузеры, такие как Firefox, Internet Explorer, Safari, Opera или Chrome, применяют соответствующий стиль, когда курсор (указатель мыши) наводится на элемент.
Замечания по использованию
На сенсорных экранах :hover
проблемный или не работает. В зависимости от браузера, псевдокласс :hover
может никогда не сработать, или сработать на некоторое время после нажатия на элемента, или может продолжать действовать даже остаться после того, как пользователь коснулся элемента до нажатия на другой элемент. Так как сенсорные устройства очень распространены, то веб-разработчикам очень важно не иметь контент, доступный только при наведении, так как такой контент неудобно или невозможно использовать на таких устройствах.
Псевдоклассы
- :active
- :any-link
- :blank
- :checked
- :current()
- :default
- :defined
- :dir()
- :disabled
- :empty
- :enabled
- :first
- :first-child
- :first-of-type
- :focus
- :focus-visible
- :focus-within
- :fullscreen
- :future
- :has()
- :host
- :host()
- :host-context()
- :hover
- :indeterminate
- :in-range
- :invalid
- :is()
- :lang()
- :last-child
- :last-of-type
- :left
- :link
- :local-link
- :not()
- :nth-child()
- :nth-col()
- :nth-last-child()
- :nth-last-col()
- :nth-last-of-type()
- :nth-of-type()
- :only-child
- :only-of-type
- :optional
- :out-of-range
- :past
- :placeholder-shown
- :read-only
- :read-write
- :required
- :right
- :root
- :scope
- :target
- :target-within
- :user-invalid
- :valid
- :visited
- :where()
Синтаксис¶
/* Selects any <a> element when "hovered" */
a:hover {
color: orange;
}
Спецификации¶
- WHATWG HTML Living Standard
- Selectors Level 4
- Selectors Level 3
- CSS Level 2 (Revision 1)
Описание и примеры¶
Пример 1. Выпадающее меню¶
С псевдоклассом :hover
вы можете создавать сложные каскадные алгоритмы. Эта техника часто используется, например, чтобы создать выпадающие меню на чистом CSS (только на CSS, без использования JavaScript). Сущность этой техники — создание правил, типа следуюшего:
CSSHTML
div.menu-bar ul ul {
display: none;
}
div.menu-bar li:hover > ul {
display: block;
}
<div class="menu-bar">
<ul>
<li>
<a href="example.html">Меню</a>
<ul>
<li>
<a href="example.html">Ссылка</a>
</li>
<li>
<a class="menu-nav" href="example.html"
>Подменю</a
>
<ul>
<li>
<a class="menu-nav" href="example.html"
>Подменю</a
>
<ul>
<li><a href="example.html">Ссылка</a></li>
<li><a href="example.html">Ссылка</a></li>
<li><a href="example.html">Ссылка</a></li>
<li><a href="example.html">Ссылка</a></li>
</ul>
</li>
<li><a href="example.html">Ссылка</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
Смотрите полный пример выпадающего меню, основанный на CSS.
Пример 2. Галерея полноразмерных изображений и превью¶
Вы можете использовать псевдокласс :hover
, чтобы создать галерею изображений с полноразмерными картинками, показываемыми при наведении на них мыши. Посмотрите это демо.
Пример 3¶
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>hover</title>
<style>
a:link {
color: #0000d0; /* Цвет ссылок */
padding: 2px; /* Поля вокруг текста */
}
a:hover {
background: #786b59; /* Цвет фона под ссылкой */
color: #ffe; /* Цвет ссылки */
}
</style>
</head>
<body>
<p><a href="1.html">Ссылка 1</a></p>
<p><a href="2.html">Ссылка 2</a></p>
<p><a href="3.html">Ссылка 3</a></p>
</body>
</html>
В данном примере псевдокласс :hover
применяется к ссылке (тегу <a>
), при этом меняется цвет ссылки и фона под ней. Результат:
Пример 4¶
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>hover</title>
<style>
ul {
width: 180px; /* Ширина меню */
list-style: none; /* Для списка убираем маркеры */
margin: 0; /* Нет отступов вокруг */
padding: 0; /* Убираем поля вокруг текста */
font-family: Arial, sans-serif; /* Рубленый шрифт для текста меню */
font-size: 10pt; /* Размер названий в пункте меню */
}
li ul {
position: absolute; /* Подменю позиционируются абсолютно */
display: none; /* Скрываем подменю */
margin-left: 165px; /* Сдвигаем подменю вправо */
margin-top: -2em; /* Сдвигаем подменю вверх */
}
li a {
display: block; /* Ссылка как блочный элемент */
padding: 5px; /* Поля вокруг надписи */
text-decoration: none; /* Подчеркивание у ссылок убираем */
color: #666; /* Цвет текста */
border: 1px solid #ccc; /* Рамка вокруг пунктов меню */
background-color: #f0f0f0; /* Цвет фона */
border-bottom: none; /* Границу снизу не проводим */
}
li a:hover {
color: #ffe; /* Цвет текста активного пункта */
background-color: #5488af; /* Цвет фона активного пункта */
}
li:hover ul {
/* При выделении пункта курсором мыши отображается подменю */
display: block;
}
.brd {
border-bottom: 1px solid #ccc; /* Линия снизу */
}
</style>
</head>
<body>
<ul class="menu">
<li>
<a href="russian.html">Русская кухня</a>
<ul>
<li><a href="linkr1.html">Бефстроганов</a></li>
<li><a href="linkr2.html">Гусь с яблоками</a></li>
<li>
<a href="linkr3.html">Крупеник новгородский</a>
</li>
<li>
<a href="linkr4.html" class="brd"
>Раки по-русски</a
>
</li>
</ul>
</li>
<li>
<a href="ukrainian.html">Украинская кухня</a>
<ul>
<li><a href="linku1.html">Вареники</a></li>
<li>
<a href="linku2.html">Жаркое по-харьковски</a>
</li>
<li>
<a href="linku3.html">Капустняк черниговский</a>
</li>
<li>
<a href="linku4.html" class="brd"
>Потапцы с помидорами</a
>
</li>
</ul>
</li>
<li>
<a href="caucasus.html">Кавказская кухня</a>
<ul>
<li><a href="linkc1.html">Суп-харчо</a></li>
<li><a href="linkc2.html">Лилибдж</a></li>
<li><a href="linkc3.html">Чихиртма</a></li>
<li>
<a href="linkc4.html" class="brd">Шашлык</a>
</li>
</ul>
</li>
<li>
<a href="asia.html" class="brd"
>Кухня Средней Азии</a
>
</li>
</ul>
</body>
</html>
В данном примере псевдокласс :hover
добавляется к элементу списка (тег <li>
) для создания двухуровневого меню. Результат:
См. также¶
:link
:visited
:active
Ссылки¶
- Псевдо-класс
:hover
MDN (рус.)