对齐行中的输入

问题描述 投票:0回答:1

这与这篇文章相关:Flex 将基线内容与带有标签的输入对齐

我有可以进行输入的组件,并且我正在尝试找到将元素布局对齐的最佳方法。我希望所有输入和按钮都在一条线上(在输入上方有标签,在输入下方有提示)。

CSS 的作用域介于主机和组件之间……所以不要觉得 CSS 网格是最好的选择。我可以更改组件中的样式(但它需要位于组件内部),并且我可以更改组件外部的样式(但不希望它尝试进入)。

<div style="display: flex; flex-direction: row; align-items: baseline; gap: 8px;">
  <div class="myComponent" style="width: 100px">
    <input id="myInput" placeholder="No label" style="width: 100%; box-sizing: border-box;"/>
  </div>
  <div class="myComponent"  style="width: 100px">
    <label for="myInput" style="display: block">Hint</label>
    <input id="myInput" placeholder="test" style="width: 100%; box-sizing: border-box;"/>
    <small style="display: block">hint</small>
  </div>
  <div class="myComponent"  style="width: 100px">
    <label for="myInput" style="display: block">Long Hint</label>
    <input id="myInput" placeholder="test" style="width: 100%; box-sizing: border-box;"/>
    <small style="display: block">A really long hint that wraps</small>
  </div>
  <div class="myComponent"  style="width: 100px">
    <label for="myInput" style="display: block">No Hint</label>
    <input id="myInput" placeholder="test" style="width: 100%; box-sizing: border-box;"/>
  </div>
  <button style="text-wrap: nowrap;">My Button</button>
</div>

html css angular web-component
1个回答
0
投票

这可以通过应用

grid-template-rows: subgrid;
来完成。
这是给您的一个例子:

.my-components {
  display: grid;
  grid-template-columns: repeat(5, 100px);
  grid-rows: repeat(3, auto);
  align-items: center;
}

.my-component {
  display: grid;
  grid-row: span 3;
  grid-template-rows: subgrid;
}

.my-component label {
  margin-top: auto;
}

.my-component input {
  width: 100%;
}

.my-component input:first-child,
.my-component button {
  grid-row-start: 2;
}
<div class="my-components">
  <div class="my-component">
    <input placeholder="No label">
  </div>
  <div class="my-component">
    <label for="input-1">Hint</label>
    <input id="input-1" placeholder="test">
    <small>hint</small>
  </div>
  <div class="my-component">
    <label for="input-2">Long<br>Hint</label>
    <input id="input-2" placeholder="test">
    <small>A really long hint that wraps</small>
  </div>
  <div class="my-component">
    <label for="input-3">No Hint</label>
    <input id="input-3" placeholder="test">
  </div>
  <div class="my-component">
    <button>My Button</button>
  </div>
</div>


附注

id
label
for
必须是唯一的。

© www.soinside.com 2019 - 2024. All rights reserved.