I want my buttons and anchors look the same. But when i have long text inside an button / anchor it should break and display the text vertical centered. When there is enough space the text should also be centered.
In order to get the text centered and not overflowing when the text breaks i set the line-height:1
also i set vertical-align:1
and of course i had to set white-space: normal
otherwise the text would not break and the button would overflow.
Now i have following problem (tested with chrome): when the text is a single line it will not be centered anymore inside the anchor tag... furthermore I do not want to change the DOM (wrapping the text inside span etc..)
Can you tell my why the button behaves different than the anchor? I already checked all styles within the chrome inspector (computed -> show all). I also checked the :before
and :after
styles.
.btn{
white-space: normal !important;
height: 45px !important;
vertical-align: middle !important;
line-height: 1 !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="row">
<div class="col-xs-2">
<a href="#" class="btn btn-default">test loooooooooooooooooooongstring<a>
<br /><br />
<button class="btn btn-default">test loooooooooooooooooooongstring</button>
</div>
</div>
<br /><br /><br />
<div class="row">
<div class="col-xs-12">
Should be centered!!
<br />
<a href="#" class="btn btn-default">test string<a>
<br /><br />
<button class="btn btn-default">test string</button>
</div>
</div>
The text-align property applies to the horizontal placement of the text within the button, not the alignment of the button itself.
Other than flexbox property, we can also center align the button horizontally and vertically using a set of CSS properties. Add position: relative to the container class and position: absolute to the class containing the button. Now use left:50% and top:50% to position the button to the center of the container.
This worked for me:
.btn{
display: inline-flex;
align-items: center;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With