inline-block盒子不适合在他们的容器 [英] inline-block boxes not fitting in their container

查看:167
本文介绍了inline-block盒子不适合在他们的容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知道我在做什么,我想通过添加边框,它会适合这四个框整齐。

Not sure what I'm doing wrong, I thought that by adding border-box, it would fit those 4 boxes neatly.

http://jsfiddle.net/jzhang172/x3ftdx6n/

.ok{
width:300px;
    background:red;
    height:100px;
    box-sizing:border-box;
}

.box{
    display:inline-block; 
    box-sizing:border-box;
    width:25%;
    border:2px solid blue;
    height:100%;
}

<div class="ok">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
    
</div>

推荐答案

p>问题是 inline-block 元素在默认情况下会带有一点额外的空间。

The problem is that inline-block elements are, by default, rendered with a bit of extra space.

为什么?因为 div 设置为 inline-block 具有一些内联元素特性。

Why? Because a div set to inline-block has some inline element characteristics.

span 元素之间的空格或换行符将导致浏览器呈现的空格。

A space or line break between span elements will result in a space rendered by the browser.

同样,如果你在< p> 元素中写入文本,每次你敲击空格键或添加换行符将由浏览器呈现空格。

Similarly, if you're writing text in a <p> element, every time you hit the space bar or add a line break a space will be rendered by the browser.

这个规则同样适用于 inline-block divs。源中的空格或换行符将导致呈现空间。

This same rule applies to inline-block divs. A space or line break in the source will result in a space rendered. This creates unexpected width, which can result in an overflow or wrapping.

一个解决方案是删除源中元素之间的所有空格:

One solution is to remove all whitespace between elements in the source:

.ok {
  width: 300px;
  background: red;
  height: 100px;
  box-sizing: border-box;
}
.box {
  display: inline-block;
  box-sizing: border-box;
  width: 25%;
  border: 2px solid blue;
  height: 100%;
}

<div class="ok"><div class="box">1</div><div class="box">2</div><div class="box">3</div><div class="box">4</div></div>

另一个方法在父项上设置 font-size:0 ,如果需要,还原子项上的字体:

Another method sets font-size: 0 on the parent and, if necessary, restores the font on the child:

.ok {
  width: 300px;
  background: red;
  height: 100px;
  box-sizing: border-box;
  font-size: 0;
}
.box {
  display: inline-block;
  box-sizing: border-box;
  width: 25%;
  border: 2px solid blue;
  height: 100%;
  font-size: 16px;
}

<div class="ok">
  <div class="box">1</div>
  <div class="box">2</div>
  <div class="box">3</div>
  <div class="box">4</div>
</div>

其他选项包括负边距省略结束标签,使用注释标签 flexbox 。有关详情,请参阅此文章:

Other options include negative margins, omitting closing tags, using comment tags, floats and flexbox. See this article for more details:

  • Fighting the Space Between Inline Block Elements

这篇关于inline-block盒子不适合在他们的容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆