Reputation: 460
I want to style a div exactly like a button. I noticed that when I give the button a specific height, the text is always centered vertically.
So far i tried digging through the Chromium user agent stylesheets but was not successful. -webkit-appereance: button
also did not do the trick.
Here is a demo of the issue: https://codepen.io/franzskuffka/pen/QzqKQx. Note that the inline-block styling gives makes sure the text is aligned vertically - the bounding box is still weird.
Which property makes the text centered vertically without any additional wrappers? What is going on here?
Upvotes: 6
Views: 993
Reputation: 176
TL;DR: It is not possible to recreate the layout created by a <button>
element using CSS. Or at least it is hidden really well.
I tested this by changing the display value to flex on a <button>
and it affected the vertical alignment. Other values like display:block
did not have an effect. It seems that there is no css value for this, it just is the default behavior and there is no way to do it for a div.
Like you, I was looking for an answer to this question. I was trying to find css property which centers vertically content in button. When I almost gave up I decided to leaf through html specification and this is what I found:
If the element is an input element, or if it is a button element and its computed value for 'display' is not 'inline-grid', 'grid', 'inline-flex', or 'flex', then the element's box has a child anonymous button content box with the following behaviors:
- The box is a block-level block container that establishes a new block formatting context (i.e., 'display' is 'flow-root').
- If the box does not overflow in the horizontal axis, then it is centered horizontally.
- If the box does not overflow in the vertical axis, then it is centered vertically. Otherwise, there is no anonymous button content box.
https://html.spec.whatwg.org/multipage/rendering.html#button-layout
Upvotes: 12
Reputation: 69
If your button doesn't have a fixed height, you can add padding to the div to center the text vertically. Add text-align: center;
to center your text horizontally.
.btn {
background-color: #000;
color: #fff;
padding: 10px;
text-align: center;
}
<div class="btn">Hello!</div>
For a button with a fixed height, you may have to have a child element.
.parent {
background-color: #000;
color: #fff;
height: 100px;
text-align: center;
width: 100px;
}
.child {
top: 50%;
transform: translateY(-50%);
}
<div class="parent">
<div class="child">Hello!</div>
</div>
There are several other methods, but these are the ones I commonly resort to. CSS-Tricks has a complete guide on centering in CSS if you'd like to try out more methods: https://css-tricks.com/centering-css-complete-guide/.
Upvotes: -1