When using padding-top to retain aspect ratio for fluid layout, how do I vertically center text to background image?

馋奶兔 提交于 2019-12-08 11:30:39

Ok so after searching high and low and no luck I have figured it out!!!

CSS

    section li {
position: relative;
width: 100%;
height: auto;
display: block;
background: url(_images/daybg_03.png) center center no-repeat;
    -webkit-background-size: contain;
    -moz-background-size: contain;
    background-size: contain;
margin: .8rem auto 0 auto;
list-style: none;
text-align: center;
font-size: 0;
padding-top: 14.95%;
}

    section ul li a {
position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
display: block;
text-decoration: none;
text-align: center;
background: rgba(0,191,85,.5);
}

    section ul li a span {
display: block;
position: absolute;
bottom: 0;
width: 100%;
height: 50%;
line-height: 0;
font-size: 1.3rem;
color: white;
text-align: center;
background: rgba(0,159,255,.5);
    }

And the bin http://jsbin.com/enuBeyE/1/edit?html,css,output

I left the background colors in there for visual help for each container.

user56reinstatemonica8

Infinity Designs' answer works well, but only if you don't need content that spans more than one line.

If you do need content that spans more than one line inside responsive, dynamic height and width vertically centred containers with a fixed aspect ratio, there's good news and bad news:

  • Good news: there is a pure CSS method that works in GC, FF, IE7+, etc etc.
  • Bad news: the code ain't pretty: it needs four (!) wrapper elements plus a non-semantic spacer. Infinity Designs' method only needs three wrappers, so use that unless you need text wrap.

It's essentially Infinity Designs' approach to the responsive fluid aspect ratio, mixed with Kizu's approach to vertical centring on this other question, using side-by-side inline-blocks with vertical align around a nested block.

JSbin demo

Sample code:

<div class="w1">  
   <!-- make w2 <a> if like the asker you want it all to be a clickable link -->
   <span class="w2"><span class="hh"> </span>
      <span class="w3"> <!-- make w3 <a> if don't want the bkg clickable  -->
         <span class="w4"><!-- or, any block element -->
            Monday
         </span>
      </span>
   </span>
</div>
<style>

.w1 {  /* outer wrapper for aspect ratio */
    position: relative; /*or absolute*/
    display: block; /*or inline-block*/
    padding-top: 25%; /*aspect ratio*/
}

.w2 {  /* wrapper2 resets position to top */
    position: absolute;
    top: 0;
    width: 100%;
    height: 100%;
    display: block;
    }

.w3 {  /* wrapper3 and hh sit side by side */
    display: inline-block;
    width: 100%;
    text-align: center;
}
.w3, .hh {
    vertical-align: middle;
    display: inline-block;
}
.hh { height: 100% }

.w4 {  /* v.align applies to child block */
    display: block;
}

</style>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!