简体   繁体   中英

How to center an absolutely positioned element within its parent when the child element's height is unknown

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

I am trying to generate a layout that would have a thumbnail header composed of the img as a background (with the css style border-radius: 50%) and the title as a banner centered in the middle and taking the whole width. But using top 50% on the absolutely positioned div.title centers via the top edge and the div.title 's height is dependent on font size.

I am wondering if there is a way to perfectly center the title, while keeping the border-radius effect considering that the only actual known dimension is the div.item 's width and all height data is ultimately determined by .thumbnail-wrapper img and .title 's font-size

the html is

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

The 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 */
}

Thanks!

JSFiddle example

Try this CSS for centering an absolutely positioned element (ie add it to div.title ):

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

Updated your JSFiddle Demo

Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM