Change Image on Hover in CSS

How to change image on hover with CSS?

The «hover» pseudo-class is used to select and apply styles to an HTML element when a user hovers their mouse over it.

Changing an image on hover with CSS is a simple process that can add an extra layer of interactivity to the website. Here, we will learn step-by-step guide to changing an image on hover with CSS −

Prepare the images

The first step in changing an image on hover using CSS is to have the two images you want to use: the default image and the hover image. Make sure these are both saved on your website and that you know the URLs for each.

Add the default image to your HTML

Use the img tag and specify the source (src) of the image. For example −

Add a hover rule to your CSS

In the CSS file, we add a rule to change the image on hover. we will do this by targeting the div tag and specifying a :hover pseudo-class. For example −

Example

Here is an example to change the image on hover using CSS.

     

Change Image on Hover Using CSS

Conclusion

To change an image on hover using CSS is a simple yet effective way to add an extra layer of engagement to the website. It is a great way to create an interactive experience for users, which can help to keep them on the site longer and increase their overall satisfaction.

Источник

Как сделать, чтобы картинка менялась при наведении на нее курсора мыши?

Заменить одну картинку на другую при наведении на неё курсора мыши.

Решение

Смена одной картинки на другую при наведении на неё курсора мыши называется эффектом перекатывания. Обычно для создания эффекта перекатывания применяется JavaScript, но в большинстве случаев вполне достаточно и CSS.

Псевдокласс :hover

Вначале разберём, как делается собственно сам эффект. Для этой цели используется псевдокласс :hover , он добавляется к желаемому селектору. Этот псевдокласс определяет стиль элемента, когда на него наводится курсор мыши, что нам как раз и требуется. Сразу отметим, что в браузере Internet Explorer версии 6 и ниже :hover работает только со ссылками, тогда как другие браузеры понимают :hover и для других элементов. Так что для универсальности придётся помещать изображение внутрь контейнера . Сам рисунок добавляется и меняется с помощью стилевого свойства background . Алгоритм действий следующий.

  1. Готовятся два изображения одинакового размера, одно для исходного вида, а второе — для его замены при эффекте перекатывания.
  2. Исходная картинка добавляется в качестве фонового рисунка к селектору A через стилевое свойство background со значением url(URI) , здесь URI — путь к графическому файлу.
  3. Присоединяем псевдокласс к селектору A и снова включаем свойство background , но в качестве значения указываем замещающее изображение.
  4. Чтобы ссылка была по размеру картинки, её следует превратить в блочный элемент с помощью свойства display со значением block , а также задать высоту и ширину ссылки.
Читайте также:  Python string перенос строки

На рис. 1 приведены два изображения: исходное (рис. 1а) и замещающее (рис. 1б).

Рис. 1аа Рис. 1бб

Рис. 1. Картинки для создания эффекта перекатывания

Остаётся собрать весь код воедино, как показано в примере 1. Чтобы ссылка не вела на какой-то определенный файл, что в данном случае излишне, добавим «заглушку» в виде символа решетки (#) к атрибуту href тега .

Пример 1. Использование псевдокласса :hover

HTML5 CSS 2.1 IE Cr Op Sa Fx

       

Приведённый способ хотя и прост в реализации, но имеет определённый недостаток. Поскольку второй рисунок загружается только при наведении курсора на ссылку, то отображение картинки происходит с некоторой паузой. Для устранения этой задержки можно использовать не два изображения, а лишь одно.

Эффект перекатывания с одним рисунком

Казалось бы имеется противоречие, ведь эффект перекатывания состоит в замене одного рисунка на другой, как же тогда обойтись одной картинкой? На самом деле изображений будет два (рис. 2), но храниться они будут в одном графическом файле.

Изображение с двумя картинками

Рис. 2. Изображение с двумя картинками

Смена одного рисунка на другой происходит сдвигом изображения по вертикали за счёт использования универсального свойства background или background-position , как показано в примере 2.

Пример 2. Изменение положения рисунка

HTML5 CSS 2.1 IE Cr Op Sa Fx

       

Для селектора A устанавливается фоновое изображение через свойство background , ширина ( width ) совпадает с рисунком, а высота (свойство height ) равна половине высоты изображения. В итоге первоначально должна отображаться зеленая вкладка целиком.

При наведении на ссылку фон смещается вверх на половину высоты картинки (40 пикселов) с помощью background-position и становится видна оранжевая вкладка.

Источник

How to Change Image on Hover Using CSS

Hovering is a technique that uses a pointing device to interact with the element. It can be used to select or style various CSS elements such as buttons, images, menus, and many more. Applying hover on an element will change its state when a mouse triggers the specified event.

The objective of this manual is to explore how to change an image on hover using CSS. So, let’s begin!

What is :hover in CSS?

The :hover is an element of pseudo-class used to change the state of HTML elements when a mouse triggers it. This CSS selector is primarily utilized to style or select elements. However, it cannot be applied to links.

The syntax of :hover is given below:

Here, “element” refers to the element in which you want to apply the hover effect.

Now, we will move to the practical example of changing the image on hover using CSS.

Example: How to Change Image on Hover Using CSS?

To change the image on hover first, add two images in the HTML section. The first image is for the active state, and the next one is for the hover state.

Step 1: Add Images

For the specified purpose, we will add two images, “image1” and “image2”, and assign the class name to the second image as “hover_img”.

Step 2: Style Images

Now, move to the CSS to set the position of both images using “position” property. We will set its position as “absolute” to position it absolutely with reference to its closest parent.

This will show the following outcome:

In the next step, we will set the second image in front of the first one. To do so, we will set the position of the image as “absolute” and set the top and left position as “0”. Using this image is placed in front of the first image, but we want to display the second image when a mouse hover on it. So, setting the display value as “none” will show the desired result:

Output of the given code is as follows:

Second image is successfully hidden behind the first image.

Now, move to the next step.

Step 3: Change Image on Hover

Next, use “:hover” and select “.img” to apply hover to the selected element. Then, assign the class name of the second image “.hover_img”. After that, inside the parentheses, set the value of the display property as “inline” which will force the element to fit in the same line:

Here is the result that demonstrates that the image is changed when user hover on it:

The above-given output indicates that we have successfully changed the image on hover using CSS.

Conclusion

Image can be changed on hover using the “:hover” pseudo-class element. To do so, add the required images in the HTML file, set them in the same position using CSS, and apply the :hover selector on them. As a result, the first image will change when hover over it. In this article, we have explained how to change an image on hover using the :hover with a practical example.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.

Источник

How to Change Image on Hover using CSS?

Change Image on hover using csschange image on hover in css

There are several methods that we can use to change images on hover. In this article, we are going to learn the two most commonly used methods which we can use to swap images on hover.

Let’s look at both methods in detail.

Change Image on Hover using the background-image Property

The basic idea of this method is to set the first image as a background image of a div element and then replace it with the second image when we hover over it simply by changing its URL.

To set an image as a background image of an element we use the background-image property and to add the hover effect we have to use the :hover pseudo-class.

Example:

Change Image on Hover using the display Property

In this method, we put the two images inside a div container and show only of one them at a time. That is, we display the first image by default and keep the second image hidden by setting the display property to none .

And when we hover over the container, we display the second image on the top of the first image simply by setting the display property to inline and setting its z-index to a higher value such as 99 or 999.

But only specifying the z-index and display property isn’t enough for this approach. Because we have to place the two images on top of each other.

To do this, we have to set the div container’s position to relative and that of the images to absolute so that we can place both the images at the same position using the top, left, bottom and right properties.

Example:

.container < width: 250px; height: 250px; border: 2px solid red; position: relative; >.container img < width: 100%; position: absolute; left: 0px; top: 0px; >.img-top < display: none; /* Hide top Image */ z-index: 99; >.container:hover .img-top< display: inline; /* Show top Image */ >

Источник

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