Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Inline-block Dimension Discrepancies

Tags:

html

css

I've got the follow HTML code:

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

And these CSS rules:

*, *: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;
}

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.

Why this behavior?

like image 882
leoMestizo Avatar asked Mar 23 '23 09:03

leoMestizo


1 Answers

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. 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/.
like image 66
Shrey Gupta Avatar answered Mar 29 '23 09:03

Shrey Gupta