2014-01-29 112 views
1

我有一个父div包括图像和文本,他们应该垂直对齐:中间,但我没有得到它的工作。不知道我做错了什么。垂直对齐图像和文本在div

找到下面我的小提琴

jsfiddle

HTML

<div class="social-cont"> 
    <div class="social-cont1"> 
     <img src="img/contact1.png" alt="contact1" width="21" height="30" /> 
    </div> <!-- end social-cont1 --> 
    <div class="social-cont2"> 
     <h6 class="social-context">Pastoor de Leijerstraat 29, 5246JA, Hintham</h6> 
    </div> <!-- end social-cont1 --> 

</div> <!-- end social-cont --> 

<div class="social-cont"> 
    <div class="social-cont1"> 
     <img src="img/contact3.png" alt="contact3" width="23" height="24" /> 
    </div> <!-- end social-cont1 --> 
    <div class="social-cont2"> 
     <h6 class="social-context">XXXXXXXXXXXXXX</h6> 
    </div> <!-- end social-cont1 --> 
</div> <!-- end social-cont --> 

CSS

.social-cont { 
    height: 100%; 
    width: 350px; 
    border-bottom: 1px solid #c1c1c1; 
    display: table; 
    background-color: salmon; 
} 

.social-cont1 img { 
    display: table-cell; 
    vertical-align: middle; 
    float: left; 
} 

h6.social-context { 
    display: table-cell; 
    vertical-align: middle; 
    color: #404040; 
    float: left; 
} 

这是我得到的预览中科达代码时:

This is what I get when previewing the code in Coda

+0

您的帖子不完整。请插入您的Coda预览。 –

+0

按照规则说明,从该jsFiddle插入代码。 – crush

+0

'vertical-align'在块级元素上不起作用。你已经漂浮了你的图片元素,这迫使它阻止关卡。阅读我的[在这里回答](http://stackoverflow.com/questions/21418400/unwanted-space-in-div-tags/21418418#answer-21418418),以更好地了解'垂直对齐'的工作原理。 – crush

回答

1

如果在容器div上使用display: inline-block并使用vertical-align: middle,则cotent将被垂直对齐。

Fiddle Here

.social-cont2, 
.social-cont1{display: inline-block; vertical-align: middle;} 

编辑:Fiddle using table-cell instead

+0

如果他想为'display'使用'table-cell',该怎么办? – crush

+0

@crush(s)他当然可以将'display:inline-block;'改为'display:table-cell;'如果内容显示为表格数据很重要。然而,在这种情况下,在divs .social-cont1 img和h6.social-context上仍然有'display:table-cell'和'vertical-align:middle'是多余的。 –

1

你不需要float: left而事实上你并不需要.social-cont1.social-cont2,你可以风格imgh6

.social-cont1 { 
    display: table-cell; 
    vertical-align: middle; 
} 

.social-cont2 { 
    display: table-cell; 
    vertical-align: middle; 
    color: #404040; 
} 

http://jsfiddle.net/fwshE/3/