如何让CSS Grid布局的联系表单中textarea跨两列?
问题解决:CSS Grid表单中textarea无法跨列显示
核心问题分析
你当前的问题出在两个关键细节上:
grid-column属性作用对象错误:Grid布局的列跨度规则仅对Grid容器的直接子元素生效,你之前把grid-column: 1 / 3写在了textarea(.contact-form__comments)上,但它的父元素contact-form__item才是Grid容器(.contact-form)的直接子项,因此该属性无法生效。- 媒体查询断点不匹配:表单在
$bp-tabport断点切换为Grid布局,但textarea的跨列样式被放在了$bp-tabland断点下,导致在平板到桌面的过渡区间内,跨列效果依然无效。
修改后的SCSS代码
&-form { display: flex; flex-direction: column; justify-content: center; width: 60%; margin: auto auto; gap: 1rem; @media only screen and (min-width: $bp-tabport) { display: grid; grid-template-columns: repeat(2, 1fr); gap: 1rem 3rem; } &__input { background-color: $color-purple; color: $color-yellow; border: none; height: 3rem; padding: 1rem; border-radius: 5px; &__submit { justify-self: center; background-color: $color-yellow; color: $color-purple; font-size: 2rem; font-weight: 600; border: none; padding: .6rem; border-radius: 5px;; width: 60%; margin: auto auto; margin-top: 2rem; grid-column: 1 / -1; } } &__item { display: flex; flex-direction: column; // 给包裹textarea的item添加跨列样式 &:has(.contact-form__comments) { @media only screen and (min-width: $bp-tabport) { grid-column: 1 / -1; } } } &__select { color: $color-yellow; padding: .6rem; background-color: $color-purple; border: none; border-radius: 5px; } &__comments { color: $color-yellow; padding: .6rem; background-color: $color-purple; border: none; border-radius: 5px; width: 100%; // 移除此处无效的grid-column属性 } }
兼容方案(不使用:has()选择器)
如果项目需要兼容不支持:has()选择器的浏览器,可以直接给包裹textarea的contact-form__item添加额外类名:
修改后的HTML片段:
<div class="contact-form__item contact-form__item--full-width"> <label for="comments">Comments</label> <textarea class="contact-form__comments" name="comments" id="comments" cols="30" rows="10">Tell us more...</textarea> </div>
对应的SCSS修改:
&__item { display: flex; flex-direction: column; } &__item--full-width { @media only screen and (min-width: $bp-tabport) { grid-column: 1 / -1; } }
效果说明
修改后,包裹textarea的整个contact-form__item会占据Grid布局的全部两列宽度,配合textarea的width:100%,就能实现textarea跨列显示的效果。同时统一了媒体查询断点,确保表单切换为Grid布局时,跨列样式立即生效。
内容的提问来源于stack exchange,提问作者surfturkey
相关产品推荐
相关产品推荐

