Search code examples
htmlcsscompass-sass

Keep a button centered over an fluid image


The last few days i tried to center a button over a fluid image. So far the position is fixed and static. The relevant HTML part looks like the following:

<ul class="moodlegrid sectionwrap">
  <li>
    <a class="ajax1" href="project1.html">
      <img title="Project 1" src="img/projectblur.jpg" alt="Project 1" />
      <img title="Project 1" src="img/project.jpg" alt="Project 1" />
      <span class="openoverlay">Click</span>
    </a>
  </li>
</ul>

The CSS looks like that:

.moodlegrid{
    li{
        a{
            position: relative;
            display:block;
            width: 100%;
            img:nth-child(1){
                display:block;
            }
            img:nth-child(2){
                display: none;
            }
            span{
                display:none;
            }
        }
        a:hover{    
            img:nth-child(2){
                display: block;
                position: absolute;
                z-index: 100;
                top:0;
                left:0;
            }
            span{
                display: block;
                position: absolute;
                text-align:center;
                top: 37%;
                left: 28%;
                z-index:101;
                @include border-radius(5px, 5px);
                @include box-shadow(black 2px 2px 10px);
            }
        }
    }
}

img{
    width:100%;
    max-width: 100%;
    height:auto !important;
}

On mouseover a second image as well as a button should float centered on top of the first image. Problem is if the viewport changes the recent version doesn't work anymore and the button isn't centered. The following article on CSS-tricks had a promising solution:

Centering in the unknown

The demo worked fine:

Centering in the unknown demo

But it utilizes inline-block elements which makes it difficult to layer images and show on top of them a centered button in the end - the elements are displayed after each other when the display:inline-block property is set. There is also the problem that in contrast to my HTML the demo aligns a child object towards a parent.

Is there a way to apply the mentioned technique to my problem, or is there a maybe even better suiting approach? Best regards Ralf


Solution

  • If I understand you rightly, you're almost there I think.

    <a> needs to be position: relative;

    <span> needs to be position: absolute;

    On the <span> if you set a specific width, and apply:

    width: 100px;
    height: 100px;
    top: 50%;
    left: 50%;
    margin-top: -50px /* Half of the height */
    margin-left: -50px; /* Half of the width */
    

    http://codepen.io/anon/pen/xjcCf

    Does that solve what you're trying to do?