How to center an absolutely positioned element inside its parent when the height of the child is unknown

In my layout, I am trying to output php generated elements. Each item retrieved from the database has a title, image, and description.

I am trying to create a layout that will have a thumbnail title consisting of img as the background (with a css border radius: 50%) and the title as a banner centered in the middle and spanning the entire width, But using the top 50% in absolutely centered centers div.title across the top, and the height of div.title depends on the font size.

I am wondering if there is a way to perfectly concentrate the heading while maintaining the effect of the radius, given that the only actual known dimension is the width of the div.item, and all the height data is ultimately determined by the .thumbnail-wrapper img and .title font-size

html

<div id="container">
  <div class="item">
    <div class="thumbnail-wrapper">
      <img />
      <div class="title">Title</div>
    </div>
    <div class="content">Content</div>
  </div>
</div>

      

CSS

#container {
    width: 600px;
}

.item {
    position: relative;
    display: inline-block;
    width: 50%;
}

.thumbnail-wrapper {
    text-align: center;
    position: relative;
}

.thumbnail-wrapper img {
    border-radius: 50%;
}

.title {
    width: 100%;
    position: absolute;
    top: 50%; /* this is the problem */
}

      

Thank!

JSFiddle example

+3


source to share


1 answer


Try this CSS for centering an absolutely positioned element (i.e. add it in div.title

):

/* centering css */
   top: 50%;
   left:50%;
   -webkit-transform:translate(-50%,-50%);
   transform:translate(-50%,-50%);

      



JSFiddle demo updated

Link

+4


source







All Articles