Html 如何垂直对齐一行文本中的行内块?

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

How to vertical align an inline-block in a line of text?

htmlvertical-alignmentcss

提问by Geoff

I want to create an inline-block that will take on some unknown width and height. (It'll have a table inside it with content dynamically generated). Further, the inline-block should be placed inside a line of text, such as "my text (BLOCK HERE)". To make it look pretty, I'm trying to make the block be vertically centered in the line. So if the block looks like this:

我想创建一个内联块,它将采用一些未知的宽度和高度。(它里面会有一个表格,内容是动态生成的)。此外,内联块应放置在一行文本内,例如“我的文本(BLOCK HERE)”。为了使它看起来漂亮,我试图使块在 line 中垂直居中。所以如果块看起来像这样:

TOP
MIDDLE
BOTTOM

Then the line of text will read: "My text ( [MIDDLE] )" (with TOP and BOTTOM above and below the line)

然后文本行将显示:“我的文本([中间])”(顶部和底部的行上方和下方)

Here's what I have so far.

这是我到目前为止所拥有的。

CSS

CSS

.example {
  background-color: #0A0;
  display: inline-block;
  margin: 2px;
  padding: 2px;
  position: relative;
  text-align: center;
}

HTML

HTML

<div class="example">TOP<br />MIDDLE<br />BOTTOM</div>

Example

例子

回答by Midas

code {
    background: black;
    color: white;
    display: inline-block;
    vertical-align: middle;
}
<p>Some text <code>A<br />B<br />C<br />D</code> continues afterward.</p>

Tested and works in Safari 5 and IE6+.

在 Safari 5 和 IE6+ 中测试和工作。

回答by clairesuzy

display: inline-blockis your friend you just need all three parts of the construct - before, the "block", after - to be one, then you can vertically align them all to the middle:

display: inline-block是你的朋友,你只需要构造的所有三个部分 - 之前,“块”,之后 - 成为一个,然后你可以将它们垂直对齐到中间:

Working Example

工作示例

(it looks like your picture anyway ;))

(无论如何它看起来像你的照片;))

CSS:

CSS:

p, div {
  display: inline-block; 
  vertical-align: middle;
}
p, div {
  display: inline !ie7; /* hack for IE7 and below */
}

table {
  background: #000; 
  color: #fff; 
  font-size: 16px; 
  font-weight: bold; margin: 0 10px;
}

td {
  padding: 5px; 
  text-align: center;
}

HTML:

HTML:

<p>some text</p> 
<div>
  <table summary="">
  <tr><td>A</td></tr>
  <tr><td>B</td></tr>
  <tr><td>C</td></tr>
  <tr><td>D</td></tr>
  </table>
</div> 
<p>continues afterwards</p>