Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

font-size changes margin, why? [duplicate]

Tags:

html

css

I'm creating a side scrolling div for mobile devices and have run into an odd problem. If you run the code below with font-size commented out for the body style there is extra margin that is added at the sides of the .scroll_item. Set the font-size to 0 and it works just fine. I'm trying to avoid setting the font size in the .scroll_item style and would rather just inherit from what comes previous to this in the page.

Why is this happening and is there another way to correct it without setting the font-size to 0?

body {
  background-color: gray;
  padding: 0;
  margin: 0;
  overflow: hidden;
  /*font-size: 0;*/
}
#scroll_cont {
  height: auto;
  background-color: red;
  margin: 0;
  padding: 0;
  white-space: nowrap;
  overflow: auto;
}
.scroll_item {
  width: 120px;
  height: 120px;
  padding: 5px;
  margin: 2px;
  background-color: blue;
  box-sizing: border-box;
  white-space: normal;
  display: inline-block;
  font-size: 20px;
  color: white;
}
<html>

<head>
  <title>Side Scroll Test</title>
  <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1, user-scalable=no">

</head>

<body>
  <div id="scroll_cont">
    <div class="scroll_item">Test1</div>
    <div class="scroll_item">Test2</div>
    <div class="scroll_item">Test3</div>
    <div class="scroll_item">Test4</div>
    <div class="scroll_item">Test5</div>
  </div>
</body>

</html>
like image 675
Paul Avatar asked Mar 06 '26 11:03

Paul


1 Answers

This is a common problem devs have with inline-blocks. An inline-block acts a little like a block, a little like inline. What does that mean? Well a block is what you're thinking it should act like right now. However, inline means it acts sort of like text. And two inline elements broken by a line break normally get white space between them automatically.

For instance:

<span>I</span>
<span>don't</span>
<span>have</span>
<span>to</span>
<span>space</span>
<span>these!</span>

This would render with white space automatically even though I didn't include any. Kinda dumb, right? But thats how it goes. There are a number of hacks and tricks to avoiding this concern. Some set a margin-right of around -4px on inline-block elements that should be stacked side by side.
Others will just use a different display type like table or flexbox. You could also try floating them left and adding a clearfix hack to them. Leave me a comment if you're still stuck and/or check out Chris Coyier's solid post about this dilemma: https://css-tricks.com/fighting-the-space-between-inline-block-elements/

like image 86
Eric N Avatar answered Mar 08 '26 00:03

Eric N



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!