inline-block
要素を使用する場合whitespace
、それらの要素の間には常に問題があります(そのスペースは約4px幅です)。
したがって、2つのdivs
はどちらも幅が50%であり、さらにwhitespace
(〜4px)は幅が100%を超えているため、壊れます。あなたの問題の例:
body{
margin: 0; /* removing the default body margin */
}
div{
display: inline-block;
width: 50%;
}
.left{
background-color: aqua;
}
.right{
background-color: gold;
}
<div class="left">foo</div>
<div class="right">bar</div>
これを修正する方法はいくつかあります。
1.それらの要素の間にスペースを入れない
body{
margin: 0; /* removing the default body margin */
}
div{
display: inline-block;
width: 50%;
}
.left{
background-color: aqua;
}
.right{
background-color: gold;
}
<div class="left">foo</div><div class="right">bar</div>
2. HTMLコメントの使用
body{
margin: 0; /* removing the default body margin */
}
div{
display: inline-block;
width: 50%;
}
.left{
background-color: aqua;
}
.right{
background-color: gold;
}
<div class="left">foo</div><!--
--><div class="right">bar</div>
3.親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;
}
<div class="parent">
<div class="left">foo</div>
<div class="right">bar</div>
</div>
4.それらの間の負のマージンの使用(好ましくない)
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;
}
<div class="left">foo</div>
<div class="right">bar</div>
5.閉鎖角度の低下
body{
margin: 0; /* removing the default body margin */
}
div{
display: inline-block;
width: 50%;
}
.left{
background-color: aqua;
}
.right{
background-color: gold;
}
<div class="left">foo</div
><div class="right">bar</div>
<hr>
<div class="left">foo</div><div class="right">
bar</div>
6. 特定の HTML終了タグをスキップする(参照のために@thirtydotに感謝)
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;
}
<ul>
<li class="left">foo
<li class="right">bar
</ul>
参照:
- CSSトリックのインラインブロック要素間のスペースとの戦い
- インラインブロック要素間の空白を削除するby David Walsh
- インラインブロック要素間のスペースを削除する方法は?
以下のようMarcosPérezGudeは@ と述べ、最善の方法は、使用することですrem
、とにいくつかのデフォルト値を追加するfont-size
にはhtml
(のようにタグHTML5Boilerplate)。例:
html{
font-size: 1em;
}
.ib-parent{ /* ib -> inline-block */
font-size: 0;
}
.ib-child{
display: inline-block;
font-size: 1rem;
}
更新:2018年が近づいているため、フレックスボックスまたはさらに優れたCSSグリッドレイアウトを使用してください。