html让两个块元素在一行,html – 两个内联块元素,每个50%宽,不适合并排在一行...

当使用inline-block元素时,在这些元素之间总会有一个空格问题(这个空间大约是4px宽)。

所以,你的两个div,都有50%的宽度,加上那个空格(〜4px)的宽度超过100%,所以它打破了。您的问题的示例:

body{

margin: 0; /* removing the default body margin */

}

div{

display: inline-block;

width: 50%;

}

.left{

background-color: aqua;

}

.right{

background-color: gold;

}

foo
bar

有几种方法可以解决:

这些元素之间没有空格

body{

margin: 0; /* removing the default body margin */

}

div{

display: inline-block;

width: 50%;

}

.left{

background-color: aqua;

}

.right{

background-color: gold;

}

foo
bar

2.使用HTML注释

body{

margin: 0; /* removing the default body margin */

}

div{

display: inline-block;

width: 50%;

}

.left{

background-color: aqua;

}

.right{

background-color: gold;

}

foo
bar

3.将parent font-size设置为0,然后向inline-block元素添加一些值

body{

margin: 0; /* removing the default body margin */

}

.parent{

font-size: 0; /* parent value */

}

.parent > div{

display: inline-block;

width: 50%;

font-size: 16px; /* some value */

}

.left{

background-color: aqua;

}

.right{

background-color: gold;

}

foo
bar

body{

margin: 0; /* removing the default body margin */

}

div{

display: inline-block;

width: 50%;

margin-right: -4px; /* negative margin */

}

.left{

background-color: aqua;

}

.right{

background-color: gold;

}

foo
bar

5.降低关闭角度

body{

margin: 0; /* removing the default body margin */

}

div{

display: inline-block;

width: 50%;

}

.left{

background-color: aqua;

}

.right{

background-color: gold;

}

foo

>

bar

foo

bar

6.跳过certain HTML结束标签(感谢@thirtydot为reference)

body{

margin: 0; /* removing the default body margin */

}

ul{

margin: 0; /* removing the default ul margin */

padding: 0; /* removing the default ul padding */

}

li{

display: inline-block;

width: 50%;

}

.left{

background-color: aqua;

}

.right{

background-color: gold;

}

  • foo
  • bar

参考文献:

作为@MarcosPérezGude said,最好的方法是使用rem,并在html标签上添加一些默认值为font-size(类似于HTML5Boilerplate)。例:

html{

font-size: 1em;

}

.ib-parent{ /* ib -> inline-block */

font-size: 0;

}

.ib-child{

display: inline-block;

font-size: 1rem;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值