【问题标题】:input and button side by side输入和按钮并排
【发布时间】:2014-06-28 07:07:08
【问题描述】:

我正在处理一个网站的标题,但我的搜索选项有问题。
我有一个 input 和一个 button 标签。
他们必须有一个vertical-align: middle; 并且应该并排。

我尝试了一些方法,但它不起作用。 有人可以解释我为什么以及如何解决这个问题吗?

HTML:

    <div id="main_search">
        <input id="main_search_input" type="text" placeholder="Suchen" />
        <button id="search_button"><img src="search.png" width="20" style="border-left: 1px solid #D7D7D7; padding: 0 0 0 5px;" alt="" title="" /></button>
    </div>

CSS:

#main_search {
    float: right;
    line-height: 60px;
    margin: 0 50px 0 0;
}
#main_search_input {
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
    height: 20px;
    line-height: 20px;
    width: 200px;
    vertical-align: middle;
    padding: 5px 10px 5px 10px !important;
}
#search_button {
    background-color: #FFF;
    border-top-right-radius: 5px;
    border-bottom-right-radius: 5px;
    height: 30px;
    padding: 5px;
    vertical-align: middle;
}

FIDDLE

【问题讨论】:

  • #main_search_input#search_button 都设置了 padding。那么当你说他们应该并排时,你想做什么?您是想让它们具有相同的高度和相同的垂直位置,还是水平相邻,或两者兼而有之?
  • 您的输入和按钮之间有一个空格,删除那个并给您的按钮一个margin: 0
  • @PetervanderWal 是否有另一种方法来解决这个问题,而不删除空格

标签: html css input vertical-alignment


【解决方案1】:

inputbutton 元素是内联元素,因此通过在代码中用换行符分隔它们,这会被有效地解释并呈现为空白字符,从而导致它们之间出现间隙。

要解决这个问题,请添加:

input, button{
    margin:0;
}

然后从 HTML 中的元素之间删除新行:

Demo Fiddle

<body>
    <div id="main_search">
        <input id="main_search_input" type="text" placeholder="Suchen" /><button id="search_button">
            <img src="https://cdn1.iconfinder.com/data/icons/TWG_Retina_Icons/24/magnifier.png" width="20" style="border-left: 1px solid #D7D7D7; padding: 0 0 0 5px;" />
        </button>
    </div>
</body>

替代方案

(也要求不设置边距,如上所述)

Float the two elements so they push up against one another

Apply a font-size:0 to #main_search so the space has a width of zero

【讨论】:

  • 删除空格后问题会解决,还有其他方法吗?
  • 答案底部列出了两种选择:)
  • 我认为将字体大小设置为 0 的最后一种选择是最好和正确的方法:)
猜你喜欢
  • 1970-01-01
  • 2018-05-28
  • 2014-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-06
  • 1970-01-01
相关资源
最近更新 更多