sanjihan sanjihan - 1 day ago 4
CSS Question

center h1 vertically and horizontally in an img element

How do you center

h1
in an
img
element, when the image is 100% of screens width and always maintaining aspect ratio? This pen shows what I mean. I've seen some answers here on SO, but the image always had width and height fixed.

Answer

to achieve your goal you need to put both img and h1 into a div and use positioning to center the h1

#headerImage {
    width:100%;        
    margin-left:auto;
    margin-right:auto;
    background-position:center;
    background-repeat:no-repeat;
   }

#greeting{
  
  padding: 0px;
  position: relative;

}

#greetin-h1{
text-align: center;
color:#000;
  position: absolute;
  top:50%;
  left:50%;
  transform:translate(-50%,-50%);
  z-index: 9999;
  
}
<div id="greeting">
    <img id="headerImage" src="http://study.com/cimages/course-image/intro-to-business-syllabus-resource-lesson-plans_138757_large.jpg" alt=""/>
    <h1 id="greetin-h1">THIS IS H1 ELEMENT</h1>
</div>

Comments