【问题标题】:Alignment image using css selector [duplicate]使用css选择器对齐图像[重复]
【发布时间】:2019-09-07 17:07:00
【问题描述】:

我正在尝试使用 CSS 选择器 :before 将图像放在文本之前。这是我的sn-p

但似乎对齐方式有点偏离。文本未与图像垂直对齐。

.resource {
 	color: #007f00;
    display: inline;
    margin-top: 20px;

}
.resource:before {
	content: '';
    width: 26px;
    height: 20px;
    display: inline-block;
    margin-right:5px;
    background-size: contain;
    background-repeat: no-repeat;
    margin-top: 19px;
    background-image:url("https://www.w3schools.com/bootstrap/cinqueterre.jpg");

}
<div class="resource">Presentation</div>

我在:before 中添加了margin-top,但它不起作用。任何帮助将不胜感激。

【问题讨论】:

    标签: html css


    【解决方案1】:

    实现目标的一种方法是使用Flexboxalign-items: center。这将使所有项目垂直居中对齐。你也可以删除你的margin-top

    .resource {
      color: #007f00;
      display: flex;
      align-items: center;
    }
    
    .resource:before {
      content: '';
      width: 26px;
      height: 20px;
      margin-right: 5px;
      background-size: contain;
      background-repeat: no-repeat;
      background-image: url("https://www.w3schools.com/bootstrap/cinqueterre.jpg");
    }
    <div class="resource">Presentation</div>

    但如果你想知道你为什么把你的图片作为::before 元素会很有趣...

    【讨论】:

    • 我也是!但这是我从客户那里收到的代码。我想知道这个 flexbox 是否可以在 IE 中工作。
    【解决方案2】:

    设置 .resource display: inline-block; 并从 .resource:before 中删除 ma​​rgin-top 并添加 vertical-align:middle 行高

    .resource {
     	color: #007f00;
      display: inline-block;
      line-height: 20px;
      vertical-align: middle;
    }
    .resource:before {
    	content: '';
        width: 26px;
        height: 20px;
        display: inline-block;
        margin-right:5px;
        background-size: contain;
        background-repeat: no-repeat;
        background-image:url("https://www.w3schools.com/bootstrap/cinqueterre.jpg");
        line-height: 20px;
        vertical-align: middle;
    }
    <div class="resource">Presentation</div>

    【讨论】:

    • 这是一种方法,但这种方法不能完美地居中对齐项目。您可以通过检查元素并将@ProX 的结果与您的结果进行比较来看到这一点。
    • @Aaron3219 是的,通过将 line-height 和 vertical-align:middle 提供给资源,它是完美的中心。
    • 不,它不是完全居中的。比较两个结果。文字在中心上方 1-2px。在两个选项卡中展开 sn-ps 并在它们之间切换。您会看到差异,如果您仔细检查,您还可以看到文本没有完全居中。
    • 是的......你可以看到它。这就是我喜欢@Aaron3219 方法的原因。
    【解决方案3】:

    如果你改变你的 HTML 和 CSS 如下,那么你可以更有效地达到同样的结果:

    .resource {
      display: flex;
    }
    
    span {
      margin-right: 5px;
      margin-top: 19px;
    }
    
    span img {
      height: 20px;
      width: 26px;
    }
    <div class="resource">
      <span><img src="https://www.w3schools.com/bootstrap/cinqueterre.jpg"/></span>
      <span>Presentation</span>
    </div>

    Here 是一个指向 JSFiddle 的链接,您也可以在其中看到结果。

    【讨论】:

      猜你喜欢
      • 2014-12-31
      • 2014-06-04
      • 2012-04-02
      • 2019-07-11
      • 1970-01-01
      • 2016-01-13
      • 2011-07-10
      • 2014-04-19
      • 2010-12-04
      相关资源
      最近更新 更多