Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Css Left property issue

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading