Box model - 2 x 50% doesn't work, I need to know why

Hey,
why this doesn’t work? There is no margin on #buttons div, no border, just nothing.
link here:https://jsbin.com/midotat/edit?html,css,output

or code here:
HTML:

   <div id="buttons">
              <div class="part a">A</div>
              <div class="part b">B</div>
    </div>

CSS:

#buttons {
  width: 335px;
  margin: auto;
}

.part {
  display: inline-block;
  text-align: center;
  width: 50%;
	/* 335 : 4 = width:83.75px, doesn't work too */ 
	/* but this work, width: 48.5% */
	/* why? */ 
}
    
.a {
    background-color: green;
}
.b {
  background-color: red;
}

I don’t completely get what you’re saying, Is this what you’re trying to achieve?

Annotation 2020-04-05 075935
If so then you need to add display: flex to your #buttons div because by default they are aligned vertically, this will align them in a row because by default flex-direction is set to row.

Also if you don’t know I would suggest you to take a look at developer tools and you’ll be able to see margins, padding, etc of your elements.

It is because the inline-block elements have white space between them. You can remove it in the HTML, or use a comment.

<div id="buttons">
  <div class="part a">A</div><div class="part b">B</div>
</div>
<!--  or -->
<div id="buttons">
  <div class="part a">A</div><!--
  --><div class="part b">B</div>
</div>

There are other ways like a negative margin or setting the font size to 0 on the parent and then setting it back on the children. However, it’s all very hacky and not something you want to use now that we have flexbox and CSS grid.

More info

1 Like