Martin J.H.
Martin J.H.

Reputation: 2205

Why does margin:0 not work on buttons?

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

Upvotes: 1

Views: 349

Answers (4)

limakid
limakid

Reputation: 81

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

Upvotes: 0

Igor Ivancha
Igor Ivancha

Reputation: 3451

as a variant, you can write:

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

Upvotes: 2

Bogdan Kuštan
Bogdan Kuštan

Reputation: 5577

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

Upvotes: 2

dfsq
dfsq

Reputation: 193261

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.

Upvotes: 4

Related Questions