0

My code is:

* {
  margin: 0;
  padding: 0;
}

aside {
  background-color: green;
  width: 20%;
  display: inline-block;
}

main {
  background-color: red;
  width: 80%;
  display: inline-block;
}
<aside>
  <h2>aside</h2>
</aside>
<main>
  <h1>main</h1>
</main>

I've set 20% width to aside block and 80% to main block, but they are not aligned horizontally as I expected. By changing aside's width to 19%, it works. My question is why it doesn't work with 20% and 80%?

nicat9507
  • 39
  • 9
  • 1
    Because you made the elements `inline-block`, _and_ there is whitespace between them. (The line break between the closing `` and the opening `
    ` tag.) https://css-tricks.com/fighting-the-space-between-inline-block-elements/ The better alternative to using inline-block would be to use flexbox or grid as basis for the layout though.
    – CBroe Apr 13 '21 at 13:08
  • @CBroe okay, I guessedd right then, only I thought it's not like that because I couldn't find that whitespace in the DOM (normally it's displayed in the inspector of the browser console, at least in FireFox). Can you tell me why I can't find it ? – TheEagle Apr 13 '21 at 13:15
  • @Programmer I think "whitespace" also includes "new line" in this case – nicat9507 Apr 13 '21 at 13:25
  • 1
    @CBroe `white-space: nowrap;` css for `body` tag also solves this problem. Any downside with that solution? – nicat9507 Apr 13 '21 at 13:27
  • 1
    As long as you re-set it to a more sensible value for the content that will be displayed inside those two elements, that should work as well. – CBroe Apr 13 '21 at 13:30
  • @CBroe so `nowrap` is not a sensible value? why? – nicat9507 Apr 13 '21 at 13:31
  • 1
    It is not a sensible value to apply to the _content_ you want to display inside those two elements, because there you usually _want_ automatic wrapping. Check the example here, https://developer.mozilla.org/en-US/docs/Web/CSS/white-space, and switch between normal and no-wrap - that a text paragraph with so much text would _not_ break into multiple lines automatically, is normally not what you’d want for your page _content_. – CBroe Apr 13 '21 at 13:32
  • @CBroe thank you. I was totally unaware of this wrapping behavior between html tags. I thought it only applies to literal texts such as `p` body. – nicat9507 Apr 13 '21 at 13:44
  • Such wrapping would not occur between normal `block` elements, but you made them inline here (inline-block, but that’s the same thing in this regard), and so they _behave_ in a similar way. You can compare this to a paragraph that contains text and images. The images are inline, they “sit” on the same baseline as the line of text they are in, and they would also automatically break to the next line, if there wasn’t enough space to display the image at the end of the current line. – CBroe Apr 13 '21 at 13:48

0 Answers0