3

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

FatalMojo
  • 435
  • 1
  • 4
  • 12
  • possible duplicate of [Using jQuery to center a DIV on the screen](http://stackoverflow.com/questions/210717/using-jquery-to-center-a-div-on-the-screen) – mehulmpt Aug 15 '14 at 14:27
  • 1
    Are you open to using some Jquery and Javascript? – J148 Aug 15 '14 at 14:27
  • 1
    Why bring JQuery into the mix when CSS can handle the positioning just fine? – JRulle Aug 15 '14 at 14:28
  • 1
    http://css-tricks.com/centering-in-the-unknown/ – Moob Aug 15 '14 at 14:29
  • Moob, it doesn't work in my context because that would require taking the img out of the flow but the img is what give the thumbnail-wrapper its height. And since I do not know it's w/h ratio in advance, I cannot give the wrapper a preset height. I could set the img as a background-image property but then I would lose the ability to apply the border-radius in the way I want. – FatalMojo Aug 15 '14 at 17:16
  • And no, I'm looking for a scriptless solution – FatalMojo Aug 15 '14 at 17:18

1 Answers1

4

Try this CSS for centering an absolutely positioned element (i.e. 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

JRulle
  • 7,448
  • 6
  • 39
  • 61
  • That's a great solution! I can live with IE9- users seeing a slightly not centered title! Thanks a lot! – FatalMojo Aug 15 '14 at 14:31
  • 1
    "Only works in IE9+" is not strictly speaking true - it also works in Firefox, Chrome, etc. :) Both the solution and nthe wartning are nevertheless valid. – Adam Aug 15 '14 at 14:32