html - 基于最宽标签对齐表单输入元素的 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
解决方案
删除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:contents
与p
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>
推荐阅读
- java - 在一组元素中找到一个复杂元素
- python - 如何使用python增加图像的大小?
- python - 如何在每个月的最后一个数据之后打印一些文本?
- r - 为什么插入符号假设 BestModel = 最小化 CV 度量而不是像 LASSO 中的最小 + 1se 的那个?
- jquery - jquery验证中不需要动态字段
- android-studio - 删除特定改造请求中的标头 Android Studio
- spring - Spring Boot SLF4j Logback
- azure-data-explorer - Kusto:连接时的全表扫描甚至连接条件是基于时间的?
- python - 训练多个分类器并比较指标
- amazon-web-services - “无法从空字符串创建路径”使用 S3 路径的配置单元中的“CREATE TABLE AS”错误