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>
2
Answers
Absolute positioning is with respect to the edges of the closest positioned ancestor.
"positioned" means "has a
position
property that is notstatic
.You haven’t set the
position
property of.image-container
, so it has the default value, which isstatic
.#image-list
hasposition: absolute
so it is the closest positioned ancestor so your positioning is done with respect to that element’s edges.To center the
<p>
element within its parent, which is .image-container
, you can addposition: relative
to.image-container
and setleft: 50%
andtransform: translateX(-50%)
on#image-list > .image-container > p
.try this example :