垂直对齐图像作为文本

时间:2013-10-21 10:34:57

标签: html css vertical-alignment

我有以下HTML ....

<div>
    <img src="" /> 
    <span>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.
    </span>
</div>

和css ......

img{
    width: 50px;
    height: 50px;
    background-color: red;
    display: inline-block;
    float: left;
    vertical-align: middle; /* not worked.... */
}
span{
    overflow: hidden;
    display: block;
    padding-left: 10px;
}

demo

正如你在演示中看到的那样,我想要垂直对齐文本的红色框。我也可以给出div的高度,例如400px。

3 个答案:

答案 0 :(得分:3)

如果我这样做,我会使用桌面显示(适用于all modern browsers)。

首先,更改您的标记,将img包装在自己的span中(这将作为我们的表格单元格):

...
<span>
    <img />
</span>
<span>
    ...
</span>

然后应用以下样式:

div {
    display:table;
}

span {
    display:table-cell;
    vertical-align:middle;
    padding-left:10px;
}

span:first-child {
    padding-left:0;
}

img {
    width:50px;
    height:50px;
    background:#f00;
}

JSFiddle demo

答案 1 :(得分:1)

使用以下CSS,使用红色方块图案的绝对定位也可以获得类似的结果:

div {
    border: 1px dotted blue;
    position: relative;
    min-height: 50px;
}
img{
    width: 50px;
    height: 50px;
    background-color: red;
    display: block;
    position: absolute;
    left: 0;
    top: 50%;
    margin-top: -25px;
}
span{
    display: block;
    margin-left: 60px;
}

在父容器上设置position: relative,然后使用绝对定位从顶部放置img 50%,然后应用margin-top: -25px以相对于父容器的高度垂直对齐它

您需要在margin-left: 60px上设置文字span,以便为方形图案留出空间。

一个优点是设计不依赖于display: table-cell

一个缺点是,对于高度小于50像素的文本块,文本将与正方形的顶部边缘对齐,根据设计要求,这可能不合适。

请参阅演示:http://jsfiddle.net/audetwebdesign/796us/

脚注:就个人而言,我认为display: table-cell是一个更强大的解决方案,只要浏览器支持它。如果不支持table-cell,则设计会优雅地降低到与文本块顶边对齐的图案,这与绝对定位选项的短文本块限制相同。

答案 2 :(得分:0)

vertical-align属性仅允许table元素或显示为table-cell的元素,如James Donelly在回答中所述, 但作为替代方案,您可以使用:

margin-top: 50%;参见示例: http://jsfiddle.net/KGg6H/19/