1

I want two buttons to be displayed right next to each other, with no border in between. The buttons are:

<button class="tButton">1</button> 
<button class="tButton">2</button> 

My naive approach for the css is:

.tButton {
    width: 50px;
    height: 50px;
    margin:0px;
    padding: 0px;
    background-color: gray;
    border: none;
}

But this leaves some space between the buttons (JSFiddle). In Firefox, the example renders as:

Around 5px between buttons

This problem goes away when I use float: left; on the buttons. But I am trying to understand the following about CSS:

Why is there any margin to begin with, even though I explicitly set margin: 0;?

Martin J.H.
  • 2,085
  • 1
  • 22
  • 37

4 Answers4

4

Because by default buttons are inline-block elements, and as any inline/inline-block elements they respect white spaces including new lines.

For this reason putting buttons on the same line gets rid of gaps:

.tButton {
    width: 50px;
    height: 50px;
    margin:0px;
    padding: 0px;
    background-color: gray;
    border: none;
}
<button class="tButton">1</button><button class="tButton">2</button> 

as well as making them float: left since in this case buttons become floated block-level elements.

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • other ways to remove the white-space [here](http://stackoverflow.com/questions/5078239/how-to-remove-the-space-between-inline-block-elements) – web-tiki Jan 03 '15 at 12:56
2

This happens with inline and inline-block elements. space is added in newline. You should change your markup, from:

<button class="tButton">1</button>
<button class="tButton">2</button> 

To

<button class="tButton">1</button><button class="tButton">2</button> 

single line fiddle

Bogdan Kuštan
  • 5,427
  • 1
  • 21
  • 30
2

as a variant, you can write:

<button class="tButton">1</button
><button class="tButton">2</button>
Igor Ivancha
  • 3,413
  • 4
  • 30
  • 39
0

The body is still a “BIG DIV” which needs to be set with margin zero and give a display:flex; so the items on its container will stack one together to the other inline. I checked your code in https://jsfiddle.net/83a2Lou0/ and it needs to be saved first before you see the effect of the changes.

I forked your same code in code pen and there the changes are saved automatically. Just add this to your CSS:

body{
margin: 0;
display: flex;
}
.tButton {
/* The same properties and values you have here. */

And that‘s it. Check here the same coding: https://codepen.io/limakid/pen/KKQRdXK

limakid
  • 71
  • 11