Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<button> has excess margin after setting padding, margin, border to 0

Tags:

html

css

The example below shows a <button> element whose parent's height is not the height of the button. What's the best way to remove this excess height while remaining semantic and also keeping the <button> inline?

If I set the button to display:block then the excess height is removed. If I set the parent's font-size to 0, then it is also removed. If I change the <button> to a <div> element, then it is fixed as well. Should I just not be semantic?

I have tested this under the stable version of Google Chrome.

.box {
  height: 30px;
  width: 30px;
  background-color: green;
}
.outer {
  background-color: blue;
}
button {
  border: 0;
  margin: 0;
  padding: 0;
}
<div class='outer'>
  <button class='box'></button>
</div>
like image 754
Sean Anderson Avatar asked Nov 18 '14 05:11

Sean Anderson


2 Answers

<button> is an inline-replaced element, so you just need to set the line-height property in CSS.

.box {
  height: 30px;
  width: 30px;
  background-color: green;
}
.outer {
  background-color: blue;
  line-height: 0;
}
button {
  border: 0;
  margin: 0;
  padding: 0;
}
<div class='outer'>
  <button class='box'></button>
</div>

I hope this helps. If you need any additional help, please comment below.

like image 179
Drazzah Avatar answered Oct 07 '22 02:10

Drazzah


This issue happened, because empty text don't rendered and baseline makes margin.
You can just add the text to your button, then it will correct rendered.
Also hardcoded vertical-align should make the trick.

.box {
  height: 30px;
  width: 30px;
  background-color: green;
}
.fix {
  vertical-align: sub;
}
.outer {
  background-color: blue;
}
button {
  border: 0;
  margin: 0;
  padding: 0;
}
<h5>Initial issue</h5>
<div class='outer'>
  <button class='box'></button>
</div>
<hr/>
<h5>Add a text</h5>
<div class='outer'>
  <button class='box'>+</button>
</div>
<hr/>
<h5>Fix by vertical-align</h5>
<div class='outer'>
  <button class='box fix'></button>
</div>
like image 39
vp_arth Avatar answered Oct 07 '22 00:10

vp_arth