CSS 如何垂直对齐行内元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5346569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 23:57:49  来源:igfitidea点击:

How to vertically align inline elements

cssinlineanchorvertical-alignment

提问by dave

I have this anchor tag that has text between to be vertically align text. I'm using this css attribute vertical-align: middle. Nothing happens tho.

我有这个锚标签,其中的文本是垂直对齐的文本。我正在使用这个 css 属性 vertical-align: middle。什么也没有发生。

采纳答案by Bazzz

You can make it inline-blockand give it a line-height:

你可以制作它inline-block并给它一个line-height

a {
    line-height: 50px;
    display: inline-block;
}

JSFiddle with working example: http://jsfiddle.net/KgqJS/

JSFiddle 与工作示例:http: //jsfiddle.net/KgqJS/

回答by alex

vertical-alignonly works on elements with display: table-cell, and that property value isn't supported in < IE8.

vertical-align仅适用于带有 的元素display: table-cell,并且 < IE8 不支持该属性值。

Known text

已知文本

If you know the text to be centred, it is rather easy. You have two options.

如果您知道要居中的文本,则相当容易。你有两个选择。

<style type="text/css">
    #container {
        padding: 10px 0;
    }
</style>
<div id="container">
    Example of some lovely<br />
    multiline text.
</div>

You can use CSS's padding to add padding top and bottom, to make the text appear in the middle. This is useful for multiline text.

您可以使用 CSS 的 padding 在顶部和底部添加 padding,使文本出现在中间。这对于多行文本很有用。

<style type="text/css">
    #container {
        height: 100px;
        line-height: 100px;
    }
</style>
<div id="container">
    Example
</div>

You can exploit the line-height property to make the text vertically centred. This only works with one line of text. You can guess what happens if there is more than 1.

您可以利用 line-height 属性使文本垂直居中。这仅适用于一行文本。你可以猜出如果超过 1 会发生什么。

Dynamic multiline text

动态多行文本

Here is where things start to get somewhat tricky, and may have you crying for tables.

这就是事情开始变得有些棘手的地方,可能会让你为桌子哭泣。

<style type="text/css">
    #container {
        display: table-cell;
        vertical-align: middle;
    }
</style>
<div id="container">
    <?php echo $content; ?>
</div>

Workaround for < IE8.

< IE8 的解决方法

Source.

来源

回答by Hussein

<div><p>test test test test<p></div>

div{
    border:1px solid red;
    width:400px;
    height:400px;
    position:relative;
}


p{
    height:30px;
    position:absolute;
    top:50%;
    margin-top:-15px; /* negative half of height*/
}

Check working example at http://jsfiddle.net/Z2ssq/1/

http://jsfiddle.net/Z2ssq/1/检查工作示例