CSS内联块大小差异 [英] CSS Inline-block Dimension Discrepancies

查看:85
本文介绍了CSS内联块大小差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下HTML代码:

I've got the follow HTML code:

<section class="container">
    <div class="search"></div>
</section>

这些CSS规则:

*, *:before, *:after {
    box-sizing: border-box;
}

body, section, div {
    margin: 0;
    padding: 0;
}

html, body { height: 100%; }

.container {
    display: inline-block;
    position: relative;
}

.search {
    display: inline-block;
    padding: 3em;
    border: 1px solid black;
}

如果检查元素,你会看到它有5px的大小...我没有建立大小。

If you inspect the section element, you'll see that it has 5px of size... I didn't establish the size. I leave that the browser calculates this automatically with the child's size.

为什么会出现这种情况?

推荐答案

原因是因为 inline-block / code>和搜索元素。想法是 inline-block 将元素视为段落中的文本;即 inline 。因此,虽然元素本身是 block 元素,浏览器在元素之间添加一些空格,因为你在 HTML中实际有空格。就像在 p 标签中添加空格在字之间添加空格,在两个之间添加空格 inline-block 元素在元素之间放置空格。

The reason is because of the inline-block that you are using for the container and search elements. The idea is that inline-block treats the elements as text in a paragraph; that is inline. So while the elements themselves are block elements, the browser adds some space between the elements because of the whitespace you actually have in your HTML. Just like how adding spaces in a p tag puts spaces between words, adding whitespace between two inline-block elements put spaces between the elements.

话虽如此,有几种方法可以解决这个问题:

That being said, there are a few ways to fix this:


  1. 最小化HTML 。可能是最简单的方法。而不是在代码中有空格,只是强制所有的一行,像这样:< section class =container>< div class =search>< / div> < / section> 。 (警告:这是未经测试的。)

  2. 添加负边距:这有点黑客,但您可以了解添加了多少空间使用您的浏览器的inspect元素的权力,比使你的负边距。也就是说,如果你的两个元素之间有4px的空间,然后应用以下: margin:-4px; 。 (默认情况下,浏览器会在 inline-block 元素之间使用4px的边距空间。)如果使用em或百分比,则可以使用响应式设计。

  3. 使用其他方式。如果您尝试 vertical-align ,则 -block 并不总是要走的路。这里有一个很好的资源: http://phrogz.net/css/vertical-align/

  1. Minimize the HTML. Possibly the simplest way. Instead of having white space in the code, just force everything to one line, like this: <section class="container"><div class="search"></div></section>. (Warning: this is untested.)
  2. Add negative margins: This is a bit of a hack, but you can find out how much space is being added by using the inspect element powers of your browser, than make that your negative margin. That is, if there is 4px of space between your two elements, then apply the following: margin:-4px;. (By default, the browser will apply 4px of margin space between inline-block elements.) If you use em or a percentage, this could work with responsive designs.
  3. Use something else. If you're trying to vertical-align, then inline-block is not always the way to go. Here's a good resource for that: http://phrogz.net/css/vertical-align/.

这篇关于CSS内联块大小差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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