简体   繁体   中英

Vertically centered text at the top of image

How do you vertically centered a text in the middle of a banner container with image tag?

My search result is using display:table/display:table-cell or display:inline-block but those solution didn't work when we have image tag. I think I have to have position absolute for text but then how to make sure it's always vertically and horizontally centered when re-sizing window?

Here is html:

<div class="banner">
  <img class="" src="http://placehold.it/1440x410">
  <div class="container">
    <div class="banner-text">
      <h1>Header Text</h1>
      <h3>Sub Header Text</h3>
      <a href="#"> CTA</a>
    </div>
  </div>
</div>

and Css as below:

.banner{
  width: 100%;
  position: relative;
}

.banner img{
    width: 100%;
}

.container{
  margin-left: auto;
  margin-right: auto;
  width: 100%;
}

.banner-text{
  position: absolute;
  top: 50%;
  left: 50%;
}

http://codepen.io/neginbasiri/pen/grEmMx

I am wondering whats your solution for this?

Thanks

just add this transform to the class listed here:

.banner-text{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%); /* or of course - translate(-50%, -50%); */
}

Fork Demo

Check out this guide for more info: Centering in CSS

The most concise way to do what you need is the following:

.banner-text {
  position: absolute;
  top: 50%;  
  left: 50%;
  transform: translate(-50%, -50%); /* add me */
}

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