Why does margin:0 not work on buttons?

Issue

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;?

Solution

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.

Answered By – dfsq

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.