Наложить текст на картинку БЕЗ растягивания картинки на 100% экрана
Нужно наложить текст на картинку, и первая же ссылка в гугле дает это:
.container {
position: relative;
text-align: center;
color: white;
}
.bottom-left {
position: absolute;
bottom: 8px;
left: 16px;
}
.top-left {
position: absolute;
top: 8px;
left: 16px;
}
.top-right {
position: absolute;
top: 8px;
right: 16px;
}
.bottom-right {
position: absolute;
bottom: 8px;
right: 16px;
}
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h2>Image Text</h2>
<p>How to place text over an image:</p>
<div class="container">
<img src="https://i.pinimg.com/originals/43/22/5a/43225aba74ba46ba733f83ec5084e73d.jpg" alt="Snow" style="width:100%;">
<div class="bottom-left">Bottom Left</div>
<div class="top-left">Top Left</div>
<div class="top-right">Top Right</div>
<div class="bottom-right">Bottom Right</div>
<div class="centered">Centered</div>
</div>
</body>
</html>
И оно успешно кладёт текст поверх картинки! Но есть фатальный недостаток -
<img src="img_snow_wide.jpg" alt="Snow" style="width:100%;">
У изображения всегда ширина - 100% от родительского объекта. Это не всегда удобно. Как сделать так, чтобы оно работало с изначальным размером изображения, не растягивая его?
Ответы (1 шт):
Автор решения: CbIPoK2513
→ Ссылка
.image {
display: block;
}
.image .wrapper {
display: inline-block;
max-width: 100%;
position: relative;
}
.bottom-left {
position: absolute;
bottom: 8px;
left: 16px;
}
.top-left {
position: absolute;
top: 8px;
left: 16px;
}
.top-right {
position: absolute;
top: 8px;
right: 16px;
}
.bottom-right {
position: absolute;
bottom: 8px;
right: 16px;
}
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
<div class="image">
<div class="wrapper">
<img src="//i.imgur.com/4sJkn2n.png">
<div class="bottom-left">Bottom Left</div>
<div class="top-left">Top Left</div>
<div class="top-right">Top Right</div>
<div class="bottom-right">Bottom Right</div>
<div class="centered">Centered</div>
</div>
</div>
<div class="image">
<div class="wrapper">
<img src="//i.imgur.com/arThuso.png">
<div class="bottom-left">Bottom Left</div>
<div class="top-left">Top Left</div>
<div class="top-right">Top Right</div>
<div class="bottom-right">Bottom Right</div>
<div class="centered">Centered</div>
</div>
</div>