why does `font-size : 0` somehow affects `line-hei

2019-08-01 07:01发布

问题:

I have encountered a strange behavior in my design today.lets me show you my code first and then discuss it

*,
*:after,
*::before {
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
body,
html {
  height: 100%;
  padding: 0;
}
#all-content,
#content-outer,
#content-inner {
  height: 100%;
  position: relative;
}
#content-inner {
  overflow-y: scroll;
}
.block {
  display: inline-block;
  font-size: 0;
  background-color: yellow;
  width: 50px;
  height: 50px;
  border: 3px solid black;
}
<div id="all-content">
  <div id="content-outer">
    <div id="content-inner">
      <div id="main-field">
        <div class="block">text</div>
        <div class="block">text</div>
        <div class="block">text</div>
        <div class="block">text</div>
      </div>
    </div>
  </div>
</div>

The thing is, with this code, there is a strange top padding applied to #main-field element. There are two ways fix this.Either with applying a line-height : 50px rule to the .block class or change the font-size to something other than zero. I want to know why is this happening since I've never encountered something strange like this behavior.

回答1:

And that's why you don't use that "hack" to remove space between block-inline elements. Even if the font size is 0 the text still has line height and probably not knowing how to behave it takes the space above the "block".

an easy solution if you still want to go with your code is to add:

vertical-align:top

to your block elements: FIDDLE

note: use float :)



回答2:

Why are you setting font-size:0? I'm guessing that you are trying one of the methods to remove white-space from between inline-block elements, but in that case, you need to specify font-size:0 on the parent of the inline-block elements (which would be #main-field) in your case and then re-specify a font-size on the inline-block elements themselves.

Seeing how you are giving your elements a fixed width, then you probably don't need this hack at all and should just be using float:left and display:block.