Shortcut To Centering And Vertically Aligning Text Over Responsive Image With Position Absolute
Objectives: Simple, Effective, and Hack-Free.
Support all major browsers
Have fallback for non-supported/legacy browsers
Feature a responsive hero image
Include and center multiple elements (headline, call-to-action, video, button, link)
You try background-cover, but realize setting and adjusting height is too much work and throwing window.height checks with javascript is overkill
You consider using Bootstrap’s .jumbotron class on the outer div, but realize it will require more work to override default bootstrap styles – not to mention messing with your super clean css flow
You have a short lapse in judgement and think “f this, Imma html4 this into table submission layout”, but you know someone is going to see it and any credibility you once had will be gone
Flexbox... right – probably needs to work in some legacy browsers because “marketing” to people outside of personal computers (see previous bullet)
position: relative on the parent
position: absolute on a child div
<div class="container-fuild hero">
<img src="img/hero.jpg" class="img-responsive" alt="use alt tags">
<div>
<h1>Center This</h1>
<a href="" title=“use title tags”>Center This</a>
</div>
</div>
h1 {
font-size: 32px;
}
.hero {
position: relative;
}
.hero div {
position: absolute;
top: 38%; /* fallback – note A below */
top: calc(50% - 32px); /* css calc – note B below */
left: 0;
text-align: center;
width: 100%;
}
Explanation (comments in above css):
Twinning “top:” Properties » Defining identical classes multiple times in the same CSS block is a common practice used to engage fallback support for legacy browsers that lack support (do not understand, do not recognize, ignore, does not compute) a css property
top: calc(expression) » “calc” takes the expression and returns a value
top: calc(50% - 32px) » vertically aligns the element based on the return value. The example expression adds the <h1> font-size of 32px
Note A » In this case, IE8 and Opera Mini does not recognize the “calc” value and ignores it. CSS cascades, so the unsupported browser ignores the second “top calc” property/value pair and settles on the first “top” property/value pair (top: 38%)
Note B » Returns the value of the expression (32px minus 50% of the targeted height (in this case the parent “hero” div)
Gotchas: Centering undefined heights in responsive design can/will-likely shoot you straight down the rabbit hole – go with it – there are massive benefits to over-engineering and over-thinking. You’ll start to rethink/reconsider your initial plan and likely find yourself coming up with simpler solutions like this.