【问题标题】:Center icon without absolute or relative positioning?没有绝对或相对定位的中心图标?
【发布时间】:2016-09-29 22:52:11
【问题描述】:

我正在尝试将 Font Awesome 图标置于 img 的中心。但是我的标记不是绝对定位或相对定位,而是布局是用 flexbox 完成的。

我已经用 CSS 属性选择器插入了图标:

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

这里是标记:

<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>

还有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;
  }
}

但我无法将图标置于 YouTube 图片的中心。我可以通过将属性选择器设置为display: flex;justify-content: center; 来使其垂直居中。这就是我能做到的。

有什么想法可以在不更改标记的情况下实现这一目标?

【问题讨论】:

标签: html css flexbox positioning font-awesome


【解决方案1】:

我认为没有绝对定位是做不到的。下面的代码可以帮助你。

#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

【讨论】:

  • 你也可以用更少的代码定位中心:position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
  • @Petroff 是的,我们可以 =)
  • @3rdthemagical 谢谢。有效。我只需要#lightgallery img#lightgallery aposition: relative
猜你喜欢
  • 2014-05-22
  • 2015-04-27
  • 2013-09-08
  • 1970-01-01
  • 2011-07-29
  • 1970-01-01
  • 1970-01-01
  • 2013-05-27
  • 1970-01-01
相关资源
最近更新 更多