html - 如何为带有 CSS 背景图片的按钮添加边距?

标签 html css

我有一个带有搜索图标背景图像的按钮,但我无法添加 margin-bottom 以使文本区域与按钮对齐。为什么向按钮添加 margin-bottom 没有任何作用?或者将文本区域与按钮对齐的正确方法是什么?

.input-area {
    width: 100%;
    height: 46px;
}

.parse-text-button {
    background: url(https://cdn1.iconfinder.com/data/icons/hawcons/32/698627-icon-111-search-32.png) no-repeat;
    width: 24px;
    height: 24px;
    border: none;
    margin-bottom: 10px;
}
<div class="input-area">
    <textarea class="input" placeholder="Enter text here"></textarea>
    <button class="parse-text-button" type="submit"></button>
</div>

最佳答案

如果您希望能够手动定位第二个元素,我建议您结合使用 position: relative 和负数 top。这允许完全控制图像的确切位置:

.input-area {
  width: 100%;
  height: 46px;
}

.parse-text-button {
  background: url(https://cdn1.iconfinder.com/data/icons/hawcons/32/698627-icon-111-search-32.png) no-repeat;
  width: 24px;
  height: 24px;
  border: none;
  position: relative;
  top: -11px;
}
<div class="input-area">
  <textarea class="input" placeholder="Enter text here"></textarea>
  <button class="parse-text-button" type="submit"></button>
</div>

或者,您可以通过给第二个元素 vertical-align: top 来对齐顶部的两个元素。这会将图像的顶部与文本区域的顶部对齐,但如果元素的高度不同(如您的示例),则可能会导致问题。

但是,考虑到您的图像与其边界有一点偏移,您可以选择使用这种方法来节省一行代码:

.input-area {
  width: 100%;
  height: 46px;
}

.parse-text-button {
  background: url(https://cdn1.iconfinder.com/data/icons/hawcons/32/698627-icon-111-search-32.png) no-repeat;
  width: 24px;
  height: 24px;
  border: none;
  vertical-align: top;
}
<div class="input-area">
  <textarea class="input" placeholder="Enter text here"></textarea>
  <button class="parse-text-button" type="submit"></button>
</div>

希望对您有所帮助! :)

关于html - 如何为带有 CSS 背景图片的按钮添加边距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46029705/

相关文章:

javascript - html页面中的文本突出显示

html - 使用浏览器调整图像大小

css - Angular : Setting a class on an element within ng-repeat based on a property of the current item

textarea - 在保持格式的同时在 TEXTAREA 中输入文本(就像 PRE 标签中的文本一样)

JQuery点击方法不起作用

jquery - 删除图标及其功能

javascript - onClick 后清除下拉值吗?

javascript - 访问 DOM 元素时 window.element 和 element 之间有什么区别

css - 你能只使用 CSS 创建这个渐变条吗?

javascript - 工具提示到动态位置以显示表格中的数据