垂直对齐CSS:在内容之前和之后:

the*_*ise 101 css css-content

我试图将链接与图像居中,但似乎无法以任何方式垂直移动内容.

<h4>More Information</h4>
<a href="#" class="pdf">File Name</a>
Run Code Online (Sandbox Code Playgroud)

图标为22 x 22px

.pdf {
    font-size: 12px;
}
.pdf:before {
    padding:0 5px 0 0;
    content: url(../img/icon/pdf_small.png);
}
.pdf:after {
    content: " ( .pdf )";
    font-size: 10px;
}
.pdf:hover:after {
    color: #000;
}
Run Code Online (Sandbox Code Playgroud)

the*_*ise 116

在阅读有关vertical-align CSS属性的建议后回答了我自己的问题.谢谢你的提示!

.pdf:before {
    padding: 0 5px 0 0;
    content: url(../img/icon/pdf_small.png);
    vertical-align: -50%;
}
Run Code Online (Sandbox Code Playgroud)

  • 尼斯.对我有用的是vertical-align:super; (2认同)

Cho*_*ett 23

我不是CSS专家,但是如果你vertical-align: middle;加入你的.pdf:before指令怎么办?

  • 真棒,中间没有用,所以我不得不使用负百分比,谢谢你的抬头! (3认同)

fas*_*ssl 17

您还可以使用表来完成此操作,例如:

.pdf {
  display: table;
}
.pdf:before {
  display: table-cell;
  vertical-align: middle;
}
Run Code Online (Sandbox Code Playgroud)

这是一个例子:https://jsfiddle.net/ar9fadd0/2/

编辑:您也可以使用flex来完成此任务:

.pdf {
  display: flex;
}
.pdf:before {
  display: flex;
  align-items: center;
}
Run Code Online (Sandbox Code Playgroud)

这是一个例子:https://jsfiddle.net/ctqk0xq1/1/

  • 这些小提琴都不适用于Chrome 52 (2认同)
  • 既不适用于OSX.http://imgur.com/bqUQ09X (2认同)

San*_*ker 10

我认为更简洁的方法是继承垂直对齐方式:

在html中:

<div class="shortcut"><a href="#">Download</a></div>
Run Code Online (Sandbox Code Playgroud)

并在CSS中:

.shortcut {
    vertical-align: middle;
}
.shortcut > a:after {
    vertical-align: inherit;
{
Run Code Online (Sandbox Code Playgroud)

这样,图标将以任何分辨率/字体大小组合正确对齐.非常适合与图标字体一起使用.


Mat*_*hew 6

使用line-height属性搞乱应该可以解决问题.我没有对此进行测试,因此确切的值可能不正确,但从1.5em开始,并以0.1为增量进行调整,直到它排成一行.

.pdf{ line-height:1.5em; }
Run Code Online (Sandbox Code Playgroud)


Dav*_*oua 6

Using flexboxes did the trick for me:

.pdf:before {
    display: flex;
    align-items: center;
    justify-content: center;
}
Run Code Online (Sandbox Code Playgroud)


Ken*_*ano 5

我今天花了很多时间试图解决这个问题,但无法使用 line-height 或 vertical-align 来解决问题。我能找到的最简单的解决方案是将 <a/> 设置为相对定位,以便它包含绝对值,并将 :after 设置为绝对定位,将其从流中移除。

a{
    position:relative;
    padding-right:18px;
}
a:after{
    position:absolute;
    content:url(image.png);
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,后图像似乎会自动居中,至少在 Firefox/Chrome 下是这样。这对于不支持 :after 的浏览器来说可能有点草率,因为 <a/> 上的间距过大。


Gja*_*jaa 5

这对我有用:

.pdf::before {
    content: url('path/to/image.png');
    display: flex;
    align-items: center;
    justify-content: center;
    height: inherit;
}
Run Code Online (Sandbox Code Playgroud)