1

I'd like to center align the text both vertically and horizontally inside this div. So it has equal padding above and below.

How do I do this with my current code? my Fiddle: http://jsfiddle.net/hr2aLrc0/

<div style="height:300px;background:url('http://placehold.it/600x300') 0 0 no-repeat;background-size:cover">
    
    <h1>Your Title</h1>
    <p>Title<br />Description</p>
    
</div>
michaelmcgurk
  • 6,367
  • 23
  • 94
  • 190
  • 1
    Proper vertical alignment is one of the longstanding missing features from CSS. See [this page](http://www.jakpsatweb.cz/css/css-vertical-center-solution.html) for workarounds. – Phylogenesis Nov 06 '15 at 13:44

2 Answers2

1

That's a standard question so a doubt that there no duplicates. ;-)

Extend your style/class with text-align: center;

<div style="text-align: center; height:300px;background:url('http://placehold.it/600x300') 0 0 no-repeat;background-size:cover">

    <h1>Your Title</h1>
    <p>Title<br />Description</p>

</div>

Vertical alignment is not that easy.

It can be done with a java script or if you wrap your div in a position: absolute styled div with top: 0px and bottom: 0px;. Then you can use margin-top: auto; margin-bottom: auto; height: ???px to center the inner div.

<div style="position: absolute; top: 0; bottom: 0; left:0; right:0; height: auto; width: auto;">
  <div style="margin-top: auto; margin-bottom:auto; text-align: center; height:300px;background:url('http://placehold.it/600x300') 0 0 no-repeat;background-size:cover">

    <h1>Your Title</h1>
    <p>Title<br />Description</p>

  </div>
</div>
Peter Paul Kiefer
  • 2,114
  • 1
  • 11
  • 16
  • Good point in the duplicates. I found this which looks more like what I require: http://jsfiddle.net/CtH9k/ – michaelmcgurk Nov 06 '15 at 13:47
  • 1
    Yes this fiddle will also work. But I'm not sure that it would work with H1 tags. But it is possible and then it would be a good solution. I have been edited my answer to show you another way. – Peter Paul Kiefer Nov 06 '15 at 13:58
1

Try this:

div {
  width: 250px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
<div style="height:300px;background:url('http://placehold.it/600x300') 0 0 no-repeat;background-size:cover">
    
    <h1>Your Title</h1>
    <p>Title<br />Description</p>
    
</div>
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331