Why is there an unexplainable gap between these inline-block div elements?
我有两个彼此相邻的内联块
CSS
1 2 3 4 5 6 7 8 9 | #container { display:inline-block; position:relative; background:rgb(255,100,0); margin:0px; width:40%; height:100px; } |
这就是我想要的样子:
在这种情况下,您的
有一些解决方案可用于解决此问题。
方法1-从标记中删除空格
示例1-将空白注释掉:(示例)
1 2 3 4 5 | text<!-- -->text<!-- -->text<!-- -->text<!-- -->text |
示例2-删除换行符:(示例)
1 | texttexttexttexttext |
示例3-在下一行关闭标签的一部分(示例)
1 2 3 4 5 | text</div >text</div >text</div >text</div >text |
示例4-在下一行关闭整个标签:(示例)
1 2 3 4 5 | text text text text text |
方法2-重置
由于
只需在父元素上设置
1 2 3 4 5 6 7 | #parent { font-size: 0; } #child { font-size: 16px; } |
这种方法效果很好,因为它不需要更改标记。但是,如果使用
方法3-将父元素设置为
在某些情况下,还可以将父元素的
这样可以有效地删除受支持的浏览器中元素之间的空格。不要忘记添加适当的供应商前缀以获取其他支持。
1 2 3 4 5 6 7 8 | .parent { display: flex; } .parent > div { display: inline-block; padding: 1em; border: 2px solid #f00; } |
1 2 3 4 5 6 7 8 | .parent { display: flex; } .parent > div { display: inline-block; padding: 1em; border: 2px solid #f00; } |
1 2 3 4 5 | text text text text text |
侧面注意事项:
使用负边距来消除
使用
您可以注释掉空格,或者更常见的解决方案是将父级的
1 2 3 4 5 6 7 8 9 | .container { display: inline-block; position: relative; background: rgb(255, 100, 0); margin: 0; width: 40%; height: 100px; float: left; } |
找到了一个不涉及Flex的解决方案,因为Flex在旧版浏览器中不起作用。
例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | .container { display:block; position:relative; height:150px; width:1024px; margin:0 auto; padding:0px; border:0px; background:#ececec; margin-bottom:10px; text-align:justify; box-sizing:border-box; white-space:nowrap; font-size:0pt; letter-spacing:-1em; } .cols { display:inline-block; position:relative; width:32%; height:100%; margin:0 auto; margin-right:2%; border:0px; background:lightgreen; box-sizing:border-box; padding:10px; font-size:10pt; letter-spacing:normal; } .cols:last-child { margin-right:0; } |
只需添加边框:
绝对可以
1 2 3 | #Div2Id { border: 2px solid #e60000; --> color is your preference } |
您需要添加
1 2 3 4 5 6 7 8 9 10 | #container { display:inline-block; position:relative; background:rgb(255,100,0); margin:0px; width:40%; height:100px; margin-right:-4px; } |
因为每当您编写