首页 > 解决方案 > margin-top 因内容而异

问题描述

我想让所有按钮的按钮容器的边距顶部为 0 或其他值。但不知何故,这似乎取决于内容。按钮内容换行越多,margin-top 的差异就越大。如何使它们全部对齐?

.buttoncontainer {
  height: 100px;
  width: 400px;
  background-color: lightblue;
  display: inline-block;
}

button {
  margin-top: 0;
  height: 100%;
  width: 60px;
  display: inline-block;
}
<div class="buttoncontainer">
  <button></button>
  <button>test</button>
  <button>test test test </button>
</div>

标签: htmlcss

解决方案


这与保证金无关。如果您vertical-align: middle为按钮设置,它们将正确对齐。

.buttoncontainer {
  height: 100px;
  width: 400px;
  background-color: lightblue;
  display: inline-block;
}

button {
  margin-top: 0;
  height: 100%;
  width: 60px;
  display: inline-block;
  vertical-align: middle;
}
<div class="buttoncontainer">
  <button></button>
  <button>test</button>
  <button>test test test </button>
</div>

因为 inline-block 元素vertical-align: baseline默认具有。如果你不设置它middle,它会像这样对齐。

在此处输入图像描述

.buttoncontainer {
  height: 100px;
  width: 400px;
  background-color: lightblue;
  display: inline-block;
}

button {
  margin-top: 0;
  height: 100%;
  width: 60px;
  display: inline-block;
  /* vertical-align: baseline; this is default */
}
<div class="buttoncontainer">
  <button>a</button>
  <button>test</button>
  <button>test test test </button>
</div>


推荐阅读