开发者

Why does setting line-height for one of two inline-block sibling divs effect both divs?

I have the following:

<div>
    <div style="display:inline-block; ">div_1</div>
    <div style="display:inline-block; line-height:20px;"开发者_运维问答>div_2</div>
</div>

Why does having a line-height property set for the second div also effects the first div? And how to correct for this i only need the second div to be effected by line-height because I need to specify a different line-height for the first div. Thanks in advance.

document.getElementById('go').onclick = function(e) {
  document.getElementById('div_2').style.lineHeight = '30px';
};
<button id="go">Go</button>
<div>
  <div style="display:inline-block;" id="div_1">div_1</div>
  <div style="display:inline-block; line-height:24px;" id="div_2">div_2</div>
</div>


With the test case, it's now crystal clear.

Add vertical-align: top to the first div:

<div style="display:inline-block; line-height:24px; vertical-align: top" id="div_1">div_1</div>

Fixed version: http://jsfiddle.net/my6Su/5/

Read this to understand the relationship between display: inline-block and vertical-align: http://blog.mozilla.com/webdev/2009/02/20/cross-browser-inline-block/

Also useful, for a visual demonstration:
http://www.brunildo.org/test/inline-block.html


Firstly, the effect of line-height is only on inline elements. When line-height is applied to block, inline-block or any other type of element that is not inline, the effects are on the inline descendant elements only.

Secondly, in a line-box (an abstract box enclosing inline elements in a line), all the inline elements are aligned along the baseline. When you change the line-height for the second div, it adds half-leading at the top (and bottom) of that inline-element. And top half-leading pushes the baseline lower, which in turn moves the first div lower.

I am not exactly sure what you are trying to achieve, but, I would recommend either using the vertical-align property or just use position relative.


<div>
    <div style="display:inline-block; line-height:10px;">div_1</div>
    <div style="display:inline-block; line-height:20px;">div_2</div>
</div>

try this. this will work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜