skip to Main Content

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


  1. Absolute positioning is with respect to the edges of the closest positioned ancestor.

    "positioned" means "has a position property that is not static.

    You haven’t set the position property of .image-container, so it has the default value, which is static.


    #image-list has position: absolute so it is the closest positioned ancestor so your positioning is done with respect to that element’s edges.

    Login or Signup to reply.
  2. 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;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search