css - 垂直对齐 div 中的文本

标签 css vertical-alignment

<分区>

下面的代码(也可以作为 a demo on JS Fiddle 获得)没有将文本放在中间,正如我理想中所希望的那样。我找不到任何方法在 div 中垂直居中文本,即使使用 margin-top 属性也是如此。我该怎么做?

<div id="column-content">
    <img src="http://i.stack.imgur.com/12qzO.png">
    <strong>1234</strong>
    yet another text content that should be centered vertically
</div>
#column-content {
    display: inline-block;
    border: 1px solid red;
    position:relative;
}
    
#column-content strong {
    color: #592102;
    font-size: 18px;
}

img {
    margin-top:-7px;
    vertical-align: middle;        
}

最佳答案

Andres Ilich 说得对。以防万一有人错过了他的评论...

A.) 如果您只有一行文本:

div
{
  height: 200px;
  line-height: 200px; /* <-- this is what you must define */
}
<div>vertically centered text</div>

B.) 如果您有多行文本:

div
{
  height: 200px;
  line-height: 200px;
}

span
{
  display: inline-block;
  vertical-align: middle;
  line-height: 18px; /* <-- adjust this */
}
<div><span>vertically centered text vertically centered text vertically centered text vertically centered text vertically centered text vertically centered text vertically centered text vertically centered text vertically centered text vertically centered text</span></div>

关于css - 垂直对齐 div 中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9249359/

相关文章:

CSS:无法让文本在框中垂直对齐

html - 在图像悬停时显示文本(垂直居中)

css - 在 div/img 上垂直和水平居中文本

javascript - 侧边栏导航不显示

html - 在页面上居中(垂直和水平)显示一张图像(尺寸未知)

CSS - 展开 div

jquery - 不考虑页面宽度的背景图像( Bootstrap )

html - 垂直对齐移动分辨率

javascript - 使用 CSS 淡化 HTML <a> anchor 标记

带有文件上传的html表单