Inline-block elements and vertical-align reasoning

不打扰是莪最后的温柔 提交于 2020-01-30 11:34:30

问题


I have 2 div boxes next to each other using display: inline-block.

Without content both inline-block divs are vertically aligned to top.

If both have content they also vertically align to top.

If only one of them has text content then the div box that has text content is vertically aligned to bottom while the one wihtout any text content remains vertically aligned to top.

If one box has plain text content and the other has e.g. an input field or a header tag then the box with only text content moves down only slighly (maybe 2 or 3px) while the one with the input or header tag stays on top.

Please see jsfiddle link below

Why did the creators do this instead of always aligning them to top? Is there a deeper reason behind this?


回答1:


UPDATE:

In your example just add:

.content_boxes{
    width: 400px;
    height: 200px;
    background: lightgreen;
    display: inline-block;
    vertical-align:top;
}

Fiddle:

http://jsfiddle.net/genwQ/1/

You have to set vertical-align:top; to each element is display:inline-block;. Careful not to confuse: it is the element, NOT the parent.

Example:

ul li {
    display:inline-block;
    vertical-align:top;
}

Demo:

http://jsfiddle.net/X3RLB/

Realize that an unwanted space appears between your inline-block elements. This space CANNOT be removed with the margin:0px; property. To remove them you must add a comment tag between inline-block the elements.

Example:

<div id="content_cnt">
    <div class="content_boxes"></div><!--
    --><div class="content_boxes">dsasda</div>
</div>

Fiddle:

http://jsfiddle.net/genwQ/2/



来源:https://stackoverflow.com/questions/23863440/inline-block-elements-and-vertical-align-reasoning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!