Наложение при наведении на изображение
С помощью CSS можно создавать эффекты наложения, которые появляются при наведении курсора на изображение. Наложение размещается поверх изображения с помощью абсолютного позиционирования внутри относительного контейнера. Разные переходы управляют тем, как появляется наложение — оно может плавно появляться или выезжать с любой стороны.
Плавное появление текста
В этом примере при наведении плавно появляется тёмное наложение с белым текстом поверх изображения. Наложение использует opacity с переходом для создания плавного эффекта появления.
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.container {
position: relative;
width: 50%;
}
.image {
display: block;
width: 100%;
height: auto;
}
.overlay {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 100%;
width: 100%;
opacity: 0;
transition: .5s ease;
background-color: rgba(0,0,0,0.5);
}
.container:hover .overlay {
opacity: 1;
}
.text {
color: white;
font-size: 20px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
</style>
</head>
<body>
<h2>Fade in Overlay</h2>
<div class="container">
<img src="img_avatar.png" alt="Avatar" class="image">
<div class="overlay">
<div class="text">Hello World</div>
</div>
</div>
</body>
</html>
Плавное появление блока
В этом примере при наведении прозрачность изображения снижается, а в центре появляется цветной блок с текстом.
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.container {
position: relative;
width: 50%;
}
.image {
opacity: 1;
display: block;
width: 100%;
height: auto;
transition: .5s ease;
backface-visibility: hidden;
}
.middle {
transition: .5s ease;
opacity: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
.container:hover .image {
opacity: 0.3;
}
.container:hover .middle {
opacity: 1;
}
.text {
background-color: #04AA6D;
color: white;
font-size: 16px;
padding: 16px 32px;
}
</style>
</head>
<body>
<h2>Fade in a Box</h2>
<div class="container">
<img src="img_avatar.png" alt="Avatar" class="image" style="width:100%">
<div class="middle">
<div class="text">John Doe</div>
</div>
</div>
</body>
</html>
Выезд сверху
В этом примере при наведении тёмное наложение выезжает вниз с верхней части изображения с помощью перехода height.
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.container {
position: relative;
width: 50%;
}
.image {
display: block;
width: 100%;
height: auto;
}
.overlay {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background-color: rgba(0,0,0,0.5);
overflow: hidden;
width: 100%;
height: 0;
transition: .5s ease;
}
.container:hover .overlay {
height: 100%;
}
.text {
white-space: nowrap;
color: white;
font-size: 20px;
position: absolute;
overflow: hidden;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
</style>
</head>
<body>
<h2>Slide in Overlay from the Top</h2>
<div class="container">
<img src="img_avatar.png" alt="Avatar" class="image">
<div class="overlay">
<div class="text">Hello World</div>
</div>
</div>
</body>
</html>
Выезд снизу
В этом примере при наведении тёмное наложение выезжает вверх с нижней части изображения.
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.container {
position: relative;
width: 50%;
}
.image {
display: block;
width: 100%;
height: auto;
}
.overlay {
position: absolute;
bottom: 100%;
left: 0;
right: 0;
background-color: rgba(0,0,0,0.5);
overflow: hidden;
width: 100%;
height: 0;
transition: .5s ease;
}
.container:hover .overlay {
bottom: 0;
height: 100%;
}
.text {
white-space: nowrap;
color: white;
font-size: 20px;
position: absolute;
overflow: hidden;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
</style>
</head>
<body>
<h2>Slide in Overlay from the Bottom</h2>
<div class="container">
<img src="img_avatar.png" alt="Avatar" class="image">
<div class="overlay">
<div class="text">Hello World</div>
</div>
</div>
</body>
</html>
Выезд слева
В этом примере при наведении тёмное наложение выезжает слева от изображения с помощью перехода width.
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.container {
position: relative;
width: 50%;
}
.image {
display: block;
width: 100%;
height: auto;
}
.overlay {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background-color: rgba(0,0,0,0.5);
overflow: hidden;
width: 0;
height: 100%;
transition: .5s ease;
}
.container:hover .overlay {
width: 100%;
}
.text {
white-space: nowrap;
color: white;
font-size: 20px;
position: absolute;
overflow: hidden;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
</style>
</head>
<body>
<h2>Slide in Overlay from the Left</h2>
<div class="container">
<img src="img_avatar.png" alt="Avatar" class="image">
<div class="overlay">
<div class="text">Hello World</div>
</div>
</div>
</body>
</html>
Выезд справа
В этом примере при наведении тёмное наложение выезжает справа от изображения.
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.container {
position: relative;
width: 50%;
}
.image {
display: block;
width: 100%;
height: auto;
}
.overlay {
position: absolute;
bottom: 0;
left: 100%;
right: 0;
background-color: rgba(0,0,0,0.5);
overflow: hidden;
width: 0;
height: 100%;
transition: .5s ease;
}
.container:hover .overlay {
width: 100%;
left: 0;
}
.text {
white-space: nowrap;
color: white;
font-size: 20px;
position: absolute;
overflow: hidden;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
</style>
</head>
<body>
<h2>Slide in Overlay from the Right</h2>
<div class="container">
<img src="img_avatar.png" alt="Avatar" class="image">
<div class="overlay">
<div class="text">Hello World</div>
</div>
</div>
</body>
</html>
Переворот изображения
Вы можете отразить изображение по горизонтали, когда пользователь наводит на него курсор. Для этого используется свойство CSS transform со значением scaleX(-1), чтобы зеркально отразить изображение.
Пример
Наведите курсор на изображение, чтобы отразить его по горизонтали.
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
img:hover {
transform: scaleX(-1);
}
</style>
</head>
<body>
<h2>Flip an Image</h2>
<p>Move your mouse over the image.</p>
<img src="madrid.jpg" alt="Madrid" width="400" height="300">
</body>
</html>
Адаптивная галерея изображений
CSS можно использовать для создания адаптивных галерей изображений. В этом примере используются медиазапросы, чтобы перестраивать изображения при разных размерах экрана. Измените размер окна браузера, чтобы увидеть эффект.
Совет: подробнее об адаптивном веб-дизайне читайте в руководстве по адаптивному веб-дизайну CSS.
Пример
Эта галерея показывает четыре изображения в ряд на больших экранах, по два в ряд на средних экранах и по одному в ряд на маленьких экранах.
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.gallery {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.gallery-item {
border: 1px solid #ccc;
margin: 10px;
width: calc(25% - 20px);
}
.gallery-item a {
display: block;
}
.gallery-item img {
width: 100%;
height: auto;
}
.desc {
padding: 15px;
text-align: center;
}
@media only screen and (max-width: 768px) {
.gallery-item {
width: calc(50% - 20px);
}
}
@media only screen and (max-width: 480px) {
.gallery-item {
width: calc(100% - 20px);
}
}
</style>
</head>
<body>
<h2>Responsive Image Gallery</h2>
<h4>Resize the browser window to see the effect!</h4>
<div class="gallery">
<div class="gallery-item">
<a target="_blank" href="https://prompt-cookbook.com">
<img src="img_5terre.jpg" alt="Cinque Terre" width="600" height="400">
</a>
<div class="desc">Cinque Terre</div>
</div>
<div class="gallery-item">
<a target="_blank" href="https://prompt-cookbook.com">
<img src="img_forest.jpg" alt="Forest" width="600" height="400">
</a>
<div class="desc">Green Forest</div>
</div>
<div class="gallery-item">
<a target="_blank" href="https://prompt-cookbook.com">
<img src="img_lights.jpg" alt="Northern Lights" width="600" height="400">
</a>
<div class="desc">Northern Lights</div>
</div>
<div class="gallery-item">
<a target="_blank" href="https://prompt-cookbook.com">
<img src="img_mountains.jpg" alt="Mountains" width="600" height="400">
</a>
<div class="desc">Mountains</div>
</div>
</div>
<p>Here we use media queries to re-arrange the images on different screen sizes:</p>
<ul>
<li>If screen is larger than 768px wide - show four images side by side</li>
<li>If screen is smaller than 768px - show two images side by side</li>
<li>If screen is smaller than 480px - stack the images vertically (100%)</li>
</ul>
</body>
</html>