I need centered text into images. How can I do this?
This is my HTML markup:
<ul >
<li><a href="#"><img src="images/bouquets.jpeg" alt=""><p >Букети</p></a></li>
<li><a href="#"><img src="images/natural_flowers.jpeg" alt=""><p >Живі квіти</p></a></li>
<li><a href="#"><img src="images/own_bouquet.png" alt=""><p >"Свій" букет</p></a></li>
</ul>
CodePudding user response:
You have to set position:relative
to the parent of your position:absolute
child (here it is .collection li a
instead of .collection
).
Then you can set your element with top
, left
, bottom
and right
.
To horizontally center an absolute positioned element, you can use :
left:0;
right:0;
margin-left: auto;
margin-right: auto;
Also, instead of selecting .col-img1, .col-img2, .col-img3{}
, you can select every class staring with col-img
with the selector [class^="col-img"]{}
.
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: "Source Sans Pro", sans-serif;
background-color: white;
color: #351f21;
}
.collection {
list-style: none;
display: flex;
justify-content: center;
}
.collection li a {
position: relative;
}
[class^="col-img"] {
background-color: #cccccc;
height: 145px;
width: 210px;
}
.col-text {
background-color: #a9bfe4;
height: 35px;
width: 140px;
text-decoration: none;
color: white;
text-align: center;
align-items: center;
position: absolute;
bottom: 10px;
left:0;
right:0;
margin-left: auto;
margin-right: auto;
}
<ul >
<li><a href="#"><img src="https://via.placeholder.com/400x300" alt=""><p >Букети</p></a></li>
<li><a href="#"><img src="https://via.placeholder.com/400x300" alt=""><p >Живі квіти</p></a></li>
<li><a href="#"><img src="https://via.placeholder.com/400x300" alt=""><p >"Свій" букет</p></a></li>
</ul>
CodePudding user response:
Your anchor tag has to be position: relative
and the overlay has to be position: absolute
.
By setting left: 0
and right: 0
of your overlay, it uses the whole available width. (If you want to have a gap on the sides, just set them to something higher than zero. In the code given above, it's set to 10px
) To center the text, you can use text-align: center
.
a {
display: block;
position: relative;
width: 200px;
height: 200px;
}
img {
width: 100%;
}
.overlay {
position: absolute;
bottom: 10px;
left: 10px;
right: 10px;
background-color: blue;
color: white;
text-align: center;
}
<a >
<img src="https://via.placeholder.com/300">
<div >This is my div</div>
</a>