CSS:将一个与输入框垂直对齐高度完美的按钮附加到输入框

3
假设我不想使用Bootstrap,那么如何实现输入框与按钮的完美垂直对齐?当我尝试时,按钮会出现垂直错位。我不想使用“hack”来调整上边距以解决这个问题,因为我担心它在所有浏览器上都看起来不好。Bootstrap是如何实现这种神奇的效果的?
我的目标是实现以下效果:

vertical-align 怎么样? - Sebastian Simon
2
你能展示一下你的代码吗?它有问题吗? - mmgross
3个回答

2

我认为答案是使用box-sizing: border-box,就像Bootstrap一样。这适用于所有现代浏览器:

<input type="text" placeholder="Your text here">
<button>Button</button>

 

input{
    float: left;
    height: 30px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}
button{
    float: left;
    height: 30px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

http://jsfiddle.net/4dgzbc3y/


完美,box-sizing 修复了在 Chrome 中对齐的元素在 Firefox 上偏移一个像素的问题。 - SexxLuthor

1
你需要使用一个容器,并将其显示为表格单元格(工作的jsFiddle):
标记:
<div class="container">
    <input type="text" placeholder="Your text here">
    <div class="button">
        <a>Button</a>
    </div>
</div>

CSS:
.container{
    display:inline-table;
    vertical-align:middle;
}
input{
    display:table-cell;
    padding:5px;
}
.button{
    display:table-cell;
    background:gray;
    padding:5px;
}

注意: 记得要让字体大小和填充相同。为了使其看起来更加流畅,你可以像bootstrap一样将外部角落圆润 :)

最近的Firefox,Chrome或Safari中看起来没有完美对齐。 - mmgross
@mmgross 或者... IE11。 =( 出现问题了。 - Katana314
我正在修复IE11的问题,最新版本的Chrome和Firefox在我的电脑上都能正常工作。 - Yotam Omer
我在Chrome上的屏幕截图(v15)如下所示:https://www.dropbox.com/s/m45rsl4nwxxpwr1/Screenshot%202015-04-07%2003.04.12.png?dl=0 - mmgross

0

有一个具有明确高度的输入框和按钮。在它们之间需要添加注释以“连接”inputbutton,否则它们之间会有一个丑陋的空格。

.target {
  height: 2em;
}

.target * {
  height: 100%;
  display:inline-block;
  border:none;
  outline:none;
}

.target input {
  width:79%;
  background-color:black;
  padding-left: 5px;
}

.target button {
  width:10%;
  background-color: orange;
  box-sizing: margin-box;
  padding: 0; margin: 0;
  border-top: 2px orange;
}
<div class="target">
  <input placeholder="Foo" type="text"><!--
  --><button>Bar</button>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接