今天遇到一个问题:两个宽度和为 100% 的内联块,没有能在同一行并列显示,第二个内联块跑到了下一行,很奇怪。查其原因竟是:空格、换行造成的。
Stack Overflow 中的相似问题:
|
JSFiddle: http://jsfiddle.net/5EcPK/
- 当减小一个
inline-block
的 width 为 49% 时,divs 可以并列显示,但是之间有个空隙,显然这不是一个理想的解决方案 http://jsfiddle.net/mUKSC/ - 当将两个 divs 浮动时,也解决了这个问题 http://jsfiddle.net/VptQm/ 但是浮动布局并不是一个理想的布局方案,浮动属性本意是为了解决“文字环绕”的效果,浮动属性现在被滥用了
根本原因
When using inline-block
elements, there will always be an whitespace
issue between those elements (that space is about ~ 4px wide).
So, your two divs
, which both have 50% width, plus that whitespace
(~ 4px) is more than 100% in width, and so it breaks.
解决方案
移除 inline-block 之间的空格
<div id="left">Left</div> |
不推荐,太依靠代码格式
利用 HTML 注释
<div id="left">Left</div> |
不推荐,很奇怪的代码格式
利用闭合标签
<div class="left">foo</div> |
<ul> |
不推荐,利用代码格式的感觉都不太靠谱
设置父级元素的 font-size 为 0
.parent { |
使用负 margin 值
div { |
References
- html - Two inline-block elements, each 50% wide, do not fit side by side in a single row - Stack Overflow
- Fighting the Space Between Inline Block Elements | CSS-Tricks
– EOF –