如何在不使用填充的情况下垂直对齐跨度img和文本?

时间:2013-05-23 07:56:07

标签: css xhtml padding vertical-alignment html

HTML

<div class="cs1">
    <span class="cs2">Label</span>
    <span class="cs3"><img src="icon.png" /></span>
    <span class="cs4">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</span>
</div>

CSS

.cs1{
    width:600px; 
    height:auto; 
    background-color:#f00; 
    overflow:hidden;
}
.cs2{
    width:170px; 
    float:left;  
    height:100%;
 }

.cs3{
    width:30px;  
    float:left;    
 }
.cs4{
    width:400px;  
    float:left; 
 } 

http://jsfiddle.net/Lwmhy/1/

以上代码,输入值的长度不同。那么如何在不使用填充的情况下垂直对齐span中的值?

2 个答案:

答案 0 :(得分:2)

这是你解决的jsFiddle:

Working FIDDLE Demo

解决方案是使用表格单元格显示属性(请注意,这不适用于IE7,但它会优雅地降级):

div span {
    display: table-cell;
    vertical-align: middle;
}

..并从跨度中移除浮子和高度...

在IE7中也适用的替代解决方案:

Working FIDDLE Demo

.cs1{
    width:600px;
    background-color:#f00; 
    overflow:hidden;
    position: relative;
}

div span {
    display: block;
    float: left;
}
.cs2,
.cs3{
    width:100px;
    position: relative;
    top: 50%;
    height: 30px;
    margin-top: -15px;
}

.cs3{
    height: 80px;
    margin-top: -40px;
}

.cs4{
    width:400px;  
}

并使用javascript设置容器的高度(在我的示例中使用jQuery):

$('.cs1').height( $('.cs1').height() );

如果行具有固定的高度,您可以在CSS中添加高度,而不需要javascript:

.cs1{
    width:600px;
    height: 300px;
    background-color:#f00; 
    overflow:hidden;
    position: relative;
}

答案 1 :(得分:1)

检查this链接,通过垂直对齐图片解决了我的问题。