首页 > 解决方案 > 基于最宽标签对齐表单输入元素的 CSS 方式

问题描述

假设我有一个表格:

<form action="#">
  <p>
    <label for="name">Name:</label>
    <input type="text" placeholder="John Smith" />
  </p>

  <p>
    <label for="name">What do you think about him?:</label>
    <input type="text" placeholder="Your opinion" />
  </p>

  <p>
    <label for="name">Another Text Input:</label>
    <input type="text" placeholder="John Smith" />
  </p> 
</form> 

使用以下 CSS:

form {
  width: 400px;
}

p {
  display: flex;
}

label {
  margin-right: 10px;
}

input {
  flex-grow: 1;
}

它看起来如下:

在此处输入图像描述

我需要根据最宽的标签对齐输入的右侧。这就是我想要的:

在此处输入图像描述

我事先不知道标签的宽度,因此带有列的类似引导的解决方案在这里并不好。有没有不使用 JS 的纯 HTML/CSS 方式来实现它?

PS!!:而且我不想用table

标签: htmlcss

解决方案


删除p并使用 CSS 网格:

form {
  width: 400px;
  display:grid;
  grid-template-columns:auto 1fr;
  grid-gap:5px;
  margin:10px;
}

input {
  width:100%;
}
<form action="#">
    <label for="name">Name:</label>
    <input type="text" placeholder="John Smith" />

    <label for="name">What do you think about him?:</label>
    <input type="text" placeholder="Your opinion" />

    <label for="name">Another Text Input:</label>
    <input type="text" placeholder="John Smith" />

</form> 


<form action="#" style="width:600px;">
    <label for="name">Name:</label>
    <input type="text" placeholder="John Smith" />

    <label for="name">What do you think about him?:</label>
    <input type="text" placeholder="Your opinion" />

    <label for="name">Another Text Input:</label>
    <input type="text" placeholder="John Smith" />

</form> 

display:contentsp

form {
  width: 400px;
  display:grid;
  grid-template-columns:auto 1fr;
  grid-gap:5px;
  margin:10px;
}

input {
  width:100%;
}

p {
 display:contents;
}
<form action="#">
<p>
    <label for="name">Name:</label>
    <input type="text" placeholder="John Smith" />
</p>
<p>
    <label for="name">What do you think about him?:</label>
    <input type="text" placeholder="Your opinion" />
</p>
<p>
    <label for="name">Another Text Input:</label>
    <input type="text" placeholder="John Smith" />
</p>
</form> 


<form action="#" style="width:600px;">
<p>
    <label for="name">Name:</label>
    <input type="text" placeholder="John Smith" />
</p>
<p>
    <label for="name">What do you think about him?:</label>
    <input type="text" placeholder="Your opinion" />
</p>
<p>
    <label for="name">Another Text Input:</label>
    <input type="text" placeholder="John Smith" />
</p>
</form>


推荐阅读