warch
warch

Reputation: 2579

CSS: Vertical align text of anchor and button

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>

Upvotes: 8

Views: 3487

Answers (2)

warch
warch

Reputation: 2579

This worked for me:

.btn{
   display: inline-flex;
   align-items: center;
}

Upvotes: 8

Omar
Omar

Reputation: 527

You Should change here // you need to change 'col-xs-2' to col-xs-12 or upper because when your text is so long, the button extend extra from col-xs-2 width. do you understand?

<div class="row">
    <div class="col-xs-12">
     <a href="#" class="btn btn-default">test loooooooooooooooooooongstring<a>
    <br /><br />
   <button class="btn btn-default">test loooooooooooooooooooongstring</button>
    </div>
</div>

Upvotes: -3

Related Questions