问题
I want to align button (anchor with button style, but the same happens with buttons) vertically centered, but there seems to be a little offset.
This is the html code I use:
<div class="alert alert-info">
Text on the left
<p class="pull-right">
<a class="btn btn-default" href="#">Link</a>
</p>
</div>
This is how it looks in jsfiddle: http://jsfiddle.net/TeAvH/
回答1:
When you use pull-right
, Bootstrap is applying float:right
. This removes the element from document flow, meaning that it will no longer affect the height of its parent container. This is the first thing you need to fix. There are a few different methods, but my favorite is applying overflow:auto
to the parent element.
Now that this problem is solved, you still have to deal with the fact that the line height of the text is not the same as the height of the button. To fix that, simply assign the line height. In this case, the button has a height of 36px
, so you can use line-height:36px
.
Here's some working code (and here's the updated fiddle):
HTML
<div class="alert alert-info">
Text on the left
<a class="btn btn-default pull-right" href="#">Link</a>
</div>
CSS
div {
overflow: auto;
line-height: 36px;
}
回答2:
It appears that this happens because the button class has display:inline-block
property. Changing this to display:inline
should fix the issue.
.alert p .btn {
display:inline;
}
Updated fiddle here.
Here is the default .btn
class properties:
.btn {
display: inline-block;
padding: 6px 12px;
margin-bottom: 0;
font-size: 14px;
font-weight: bold;
line-height: 1.428571429;
text-align: center;
white-space: nowrap;
vertical-align: middle;
cursor: pointer;
border: 1px solid transparent;
border-radius: 4px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
}
回答3:
First of all, please be advised that some HTML elements do have a default margin and/or padding. More on that here.
To have more control of what's happening in this case, you could put the text and the other element inside a <div>
floating respectively to left and right.
来源:https://stackoverflow.com/questions/18169717/align-button-vertically-in-alert-field