Flex布局实现:前两个标签等宽,第三个标签占满整行
解决方案
要实现第一个与第二个label宽度相等、第三个label占满整行的效果,只需调整label的Flex属性配置即可,具体修改如下:
关键CSS调整片段
/* flex */ fieldset{ display: flex; flex-wrap: wrap; gap: 1em; } /* 前两个label平分容器宽度,减去gap的一半避免溢出 */ label:nth-child(1), label:nth-child(2) { flex: 1 1 calc(50% - 0.5em); } /* 第三个label强制占满整行 */ label:nth-child(3) { flex: 1 1 100%; }
原理说明
- 前两个label使用
calc(50% - 0.5em)作为flex基准宽度,是因为fieldset设置了gap:1em,两个元素间的间隙会占用1em宽度,减去0.5em后能保证两个元素总宽度不超过容器,同时实现宽度完全相等。 - 第三个label设置
flex-basis:100%,结合flex-wrap:wrap规则,会自动换行并占满整行宽度。
完整修正后的CSS代码
@import url('https://fonts.googleapis.com/css2?family=Montserrat+Alternates:wght@400;800&display=swap'); * { box-sizing: border-box; } body { display: flow-root; font-family: 'Montserrat Alternates', sans-serif; /* background-image: url(../images/background-cars.jpg); */ background-size: cover ; min-height: calc(100vh - 1em); /* 修正原代码的语法错误 */ background-color: saddlebrown; font-size: 0.75rem; font-weight: 400; } input, select, button { width: 100%; border-radius: 0.5em; padding: 15px; } input, select{ color: gray; } /* flex */ fieldset{ display: flex; flex-wrap: wrap; gap: 1em; } label:nth-child(1), label:nth-child(2) { flex: 1 1 calc(50% - 0.5em); } label:nth-child(3) { flex: 1 1 100%; } /* layout */ form { background-color: black; padding: 15px; color: white; width: 75%; max-width: 800px; margin: auto; border-radius: 0.5em; } button{ background-color: gold; font-weight: 800; border-radius: 0.5em; margin-top: 15px; } h1{ color: gold; font-weight: 800; font-size: 4rem; text-align: center; } legend{ font-weight: 800; } fieldset{ border-radius: 0.5em; }
注:原代码中min-height: (1vh-1em)存在语法错误,已修正为min-height: calc(100vh - 1em),保证页面最小高度计算正确。
内容的提问来源于stack exchange,提问作者Nomistake
相关产品推荐
相关产品推荐

