Html 如何使用 CSS 在固定高度的列表项内垂直对齐文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8361509/
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 11:47:52  来源:igfitidea点击:

How to vertically align text inside fixed-height list items using CSS?

htmlcss

提问by TK123

How can I vertically align the text in the following list items:

如何垂直对齐以下列表项中的文本:

http://jsfiddle.net/K2eF3/

http://jsfiddle.net/K2eF3/

<style>

ul { list-style-type: none; width: 300px; }
ul li { border: 1px solid red; height: 100px; }

</style>

<ul>
    <li>A bear</li>
    <li>A panda who eats bamboo</li>
    <li>A giraffe with a very very very very very veryvery very very very long neck</li>
</ul>

I can't use line-height because those sentences are dynamically generated and could be one line or multiline (not always singe). That's also why I can just individually target each <li>with custom padding.

我不能使用 line-height,因为这些句子是动态生成的,可以是一行或多行(并不总是单行)。这也是我可以<li>使用自定义填充单独定位每个的原因。

Vertical align middle didn't work either, after reading up on it, it appears to only target elements which explains why aligning text inside an element using it didn't work.

垂直对齐中间也不起作用,在阅读它之后,它似乎只针对目标元素,这解释了为什么使用它在元素内对齐文本不起作用。

回答by Cory Danielson

Wrap the content of each <li>in a <span>then apply the following css:

将每个的内容包裹<li>在 a 中,<span>然后应用以下 css:

ul li span {
    height: 100px;
    display: table-cell;
    vertical-align: middle;
}

http://jsfiddle.net/K2eF3/12/

http://jsfiddle.net/K2eF3/12/

回答by mrdeleon

if you are not too worried about IE7 and below, try wrapping the text with a div and adding display:table-cell, vertical-align:middleand height:100pxon the div.

如果您不太担心 IE7 及以下版本,请尝试用 div 包裹文本并在 div 上添加display:table-cell,vertical-align:middleheight:100px

回答by Paul D. Waite

Safari/Chrome and Firefox have their own implementations of the CSS Flexible Box Module, which allows this sort of layout:

Safari/Chrome 和 Firefox 有自己的CSS 弹性盒模块实现,它允许这种布局:

However, there's sadly no display:-o-box;or display:-ms-box;for Opera and Internet Explorer yet.

然而,遗憾的是,目前还没有display:-o-box;display:-ms-box;适用于 Opera 和 Internet Explorer。

回答by Ahmad Alfy

Here's my working solution.

这是我的工作解决方案

It uses jQuery to vertically align the span inside the li. To make sure the span is correctly aligned it should have the display property should have inline-block value.

它使用 jQuery 垂直对齐 li 内的跨度。为了确保跨度正确对齐,它应该具有 display 属性应该具有 inline-block 值。

If you can't change the output to the spans inside the LI I can help you doing it using jQuery.

如果您无法将输出更改为 LI 内的跨度,我可以使用 jQuery 帮助您完成此操作。