-2

I'm making a CSS based burger menu button, and I noticed that the <span> bars are vertically centered by default. Inspecting and playing around with the bars' margin keeps the elements vertically centered.

But if I try the same code and replace the <button> with a <div>, it's no more vertically aligned.

.toggle-btn {
  display: block;
  background: #eee;
  border: none;
  width: 50px;
  height: 50px;
  padding: 0;
  margin: 20px auto 30px;
}
.toggle-btn .bar {
  display: block;
  background: #000;
  width: 24px;
  height: 3px;
  margin: 0 auto;
}
.toggle-btn .bar + .bar {
  margin-top: 5px;
}
p {
  margin: 0;
  text-align: center;
}
<p>this is a button</p>
<button class="toggle-btn">
  <span class="bar"></span>
  <span class="bar"></span>
  <span class="bar"></span>
</button>

<p>this is a div</p>
<div class="toggle-btn">
  <span class="bar"></span>
  <span class="bar"></span>
  <span class="bar"></span>
</div>

This is completely new to me, and there doesn't seem to be any browser default CSS that seems to cause this. I feel like I'm missing something obvious.

I'm curious on how this happens. What causes the bars inside a <button> to be vertically centered?

DriftingSteps
  • 526
  • 1
  • 7
  • 23

3 Answers3

0

This piece of code does the trick

.toggle-btn .bar + .bar {
  margin-top: 5px;
}

It adds a margin-top to the second and third bar.

Gibin Ealias
  • 2,751
  • 5
  • 21
  • 39
  • 1
    but removing `margin-top` altogether still keeps the bars vertically centered. My question is, what is keeping them vertically centered? – DriftingSteps Mar 09 '18 at 06:46
  • Its because the ``s are no more an `inline` element but a `block` element. `.toggle-btn .bar{display: block}`. And they, by default, stacks one below another. – Gibin Ealias Mar 09 '18 at 06:48
  • @DriftingSteps centered using this `.toggle-btn{margin:50px auto;}` – Saravana Mar 09 '18 at 06:50
  • 1
    I don't think you understand what my question is. I'm talking about the black bars. Why are the black bars vertically centered inside the button? What is causing that? – DriftingSteps Mar 09 '18 at 06:53
  • Its because your parent element is a ` – Gibin Ealias Mar 09 '18 at 07:10
0

that is the default property of <button> element.if you write any content inside html <button> tag ,that will appear vertically centered.I'm added one example below.

.button-element{
 width:200px;
 height:200px;
 border:1px solid #000;
 background-color:yellow;
}

.button-child{
width:100px;
border:1px solid #000;
}
<button class="button-element">
  <span class="button-child"></div>
</button>
ADH - THE TECHIE GUY
  • 4,125
  • 3
  • 31
  • 54
-2

By default the bootstrap keeps the hamburger menu vertically. So,

.toggle-bar{ float:"top"; }

float:top **might help fix this.**