我正在尝试找到最有效的方法来将文本与div对齐。我尝试了一些方法,但似乎没有一个有效。

.推荐文本{位置:绝对;左:15px;顶部:15px;宽度:150px;高度:309px;垂直对齐:中间;文本对齐:居中;字体系列:Georgia,“Times New Roman”,Times,serif;字体样式:斜体;填充:1em 0 1em 0;}<div class=“推荐文本”>Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。在最低限度的威尼斯,quis nostrud exerciation ullamco labour nisi Ut aliquip ex a commo consequat。Duis aute irure多尔代表在voluptate velit esse cillum dolore eu fugiat nullapariator。除了你偶尔犯下的错误外,你还得承担责任,这是因为你在实验室里表现得很糟糕。</div>


当前回答

嗯,显然有很多方法可以解决这个问题。

但我有一个绝对定位的<div>,高度:100%(实际上,顶部:0;底部:0,固定宽度),显示:表格单元格无法垂直居中文本。我的解决方案确实需要内部跨度元素,但我看到许多其他解决方案也需要,所以我不妨添加它:

我的容器是一个.label,我希望数字在其中垂直居中。我这样做是通过将绝对位置放在顶部:50%,并设置行高度:0

<div class="label"><span>1.</span></div>

CSS如下:

.label {
    position:absolute;
    top:0;
    bottom:0;
    width:30px;
}

.label>span {
    position:absolute;
    top:50%;
    line-height:0;
}

在行动中看到:http://jsfiddle.net/jcward/7gMLx/

其他回答

这里有一个最适合单行文本的解决方案。

如果知道行数,它还可以对多行文本进行一些调整。

.testimonialText {
    font-size: 1em; /* Set a font size */
}
.testimonialText:before { /* Add a pseudo element */
    content: "";
    display: block;
    height: 50%;
    margin-top: -0.5em; /* Half of the font size */
}

这是一个JSFiddle。

使用flex时,请注意浏览器渲染的差异。

这对Chrome和Internet Explorer都很有效:

.外部{显示:柔性;宽度:200px;高度:200px;背景色:#ffc;}.内部{显示:柔性;宽度:50%;高度:50%;边距:自动;文本对齐:居中;对齐内容:中心;对齐项目:居中;背景色:#fcc;}活动任务</div></div>

与仅适用于Chrome的这款相比:

.外部{显示:柔性;宽度:200px;高度:200px;背景色:#ffc;}.内部{显示:柔性;宽度:50%;高度:50%;边距:自动;背景色:#fcc;}<div class=“outer”>活动任务</span></div></div>

非常简单的解决方案,我在我的项目中多次使用它:

源代码

.welcome_box{
    height: 300px;
    display: flex;
    justify-content: center;
    align-content: center;
    flex-direction: column;
    border: solid 1px #dadada;
}

<div class="welcome_box">Hello Friends</div>

输出:

谢谢你提出这个问题。很高兴分享。

这是我找到的最干净的解决方案(InternetExplorer9+),并通过使用其他答案省略的转换样式,为“偏移0.5像素”问题添加了修复。

.parent-element {
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
}

.element {
  position: relative;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}

来源:垂直对齐任何东西,只需3行CSS

这很好:

HTML

<div class="information">
    <span>Some text</span>
    <mat-icon>info_outline</mat-icon>
</div>

Sass

.information {
    display: inline-block;
    padding: 4px 0;
    span {
        display: inline-block;
        vertical-align: middle;
    }
    mat-icon {
        vertical-align: middle;
    }
}

没有和带有图像标记<mat icon>(这是一种字体)。