Using the left property in #image-list>.image-container>p
seems to center the <p>
element in the div with id #image-list
and not its parent. I do not understand what I did wrong.
btn.onclick = e => {
list = document.getElementById("image-list");
item = list.children[0];
item = item.cloneNode(true);
document.getElementById("image-list").appendChild(item);
}
#image-list {
display: flex;
gap: 4vmin;
position: absolute;
left: 50%;
top: 50%;
transform: translate(0%, -50%);
}
#image-list>.image-container>.image {
width: 40vmin;
height: 56vmin;
object-fit: cover;
object-position: 100% center;
}
#image-list>.image-container>p {
position: absolute;
color: white;
top: 25%;
left: 50%;
transform: translate(-50%, -50%);
display: block;
font-family: Times New Roman;
font-size: 2rem;
-webkit-text-stroke: 0.5px black;
}
#image-list>.image-container {
text-align: center;
position:relative;
}
<div id="image-list">
<div class="image-container">
<p>hello world</p>
<img class="image" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/800px-Image_created_with_a_mobile_phone.png" draggable="false">
</div>
</div>
<button id="btn">add image</button>
>Solution :
To center the <p>
element within its parent, which is .image-container
, you can add position: relative
to .image-container
and set left: 50%
and transform: translateX(-50%)
on #image-list > .image-container > p
.
try this example :
#image-list>.image-container {
text-align: center;
position: relative;
}
#image-list>.image-container>p {
position: absolute;
color: white;
top: 25%;
left: 50%;
transform: translateX(-50%);
display: block;
font-family: Times New Roman;
font-size: 2rem;
-webkit-text-stroke: 0.5px black;
}