Search code examples
htmlcssflexboxpositioningfont-awesome

Center icon without absolute or relative positioning?


I'm trying to center an Font Awesome icon on an img. But my markup isn't positioned absolute or relative without, but layout is done with flexbox.

I've inserted the icon with CSS Attribute selector:

a[href*="youtu"]::before {
    font-family: 'FontAwesome';
    content: "\f144";
    font-size: 2.5em;
}

And here is the markup:

<div id="lightgallery">
  <a href="http://local.wordpress.dev/wp-content/uploads/2016/09/image10.jpg"> 
    <img src="http://local.wordpress.dev/wp-content/uploads/2016/09/image10.jpg" alt="" /> 
  </a>
  <a href="http://local.wordpress.dev/wp-content/uploads/2016/09/image9.jpg"> 
    <img src="http://local.wordpress.dev/wp-content/uploads/2016/09/image9.jpg" alt="" /> 
  </a>
  <a href="http://local.wordpress.dev/wp-content/uploads/2016/09/image8.jpg"> 
    <img src="http://local.wordpress.dev/wp-content/uploads/2016/09/image8.jpg" alt="" /> 
  </a>
  <a href="https://youtu.be/5Z3Exfzz8Kk" data-poster="http://local.wordpress.dev/wp-content/uploads/2016/09/video-thumb.jpg"> 
    <img src="http://local.wordpress.dev/wp-content/uploads/2016/09/video-thumb.jpg" alt="" /> 
  </a>

And the css:

@media screen and (min-width: 48em) {
  #lightgallery a {
    width: calc(100% / 3);
    height: 240px;
  }

  #lightgallery img {
    width: 100%;
    background-image: url();
    background-repeat: no-repeat;
    height: 240px;
    object-fit: cover;
  }

  #lightgallery {
    display: flex;
    flex-wrap: wrap;
    margin: 6.25em 0;
  }
}

But I can't get the icon centered over the YouTube image. I can get it centered vertically by setting attribute selector to display: flex; and justify-content: center;. And that is as far as I can come.

Any ideas to achieve this without changing the markup?


Solution

  • I think that you can't do it without absolute positioning. Code below can help you.

    #lightgallery a {
        width: calc(100% / 3);
        height: 240px;
    
        text-decoration: none;
        position: relative;    
    }
    
    a[href*="youtu"]::before {
        font-family: 'FontAwesome';
        content: "\f144";
        font-size: 2.5em;
    
        position: absolute;      
        top: 0;
        left: 0;
        width: 100%;             
        height: 100%;            
        display: flex;             
        justify-content: center;  
        align-items: center;     
    }
    

    Demo