You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用CSS Grid让元素拉伸填满容器 实现联系表单textarea自适应

实现方案

仅需调整CSS即可实现需求,HTML结构无需修改,核心通过CSS Grid控制输入容器的行高分配,具体修改如下:

调整后的完整CSS代码

.contact-section-container {
    background: #2A6CCF;
    border-radius: 20px;
    font-family: sans-serif;
    font-size: clamp(1rem, 1.042vw, 1.25rem);
    color: white;
    width: clamp(30rem, 41.98vw, 50.375rem);
    height: clamp(30rem, 38.28125vw, 45.9375rem);
    padding: 1.5625rem 3.125rem 1.5625rem 3.125rem;
    /* 新增:让容器内部垂直排列,自动分配高度 */
    display: flex;
    flex-direction: column;
}

.contact-section-container h2 {
    font-size: 1.875rem;
    color: white;
    display:flex;
    justify-content:center;
    margin-bottom: .833em;
}

/* 新增:输入容器占满剩余高度,开启Grid布局 */
.contact-form-input-container {
    flex: 1;
    display: grid;
    grid-template-rows: auto auto 1fr auto;
    gap: 0.75em;
}

.contact-section-container div label {
    display: block;
    margin-bottom: .5em;
}

/* 原有margin-top可以删除,已经通过grid的gap统一控制间距
.contact-section-container div:nth-of-type(n+2) label{
    margin-top: .75em;
}
*/

/* 把textarea从原有选择器拆分,避免给textarea设置固定高度 */
.contact-section-container div input {
    background: #F2F2F2;
    box-shadow: 1px 1px 4px rgba(0, 0, 0, 0.15);
    border-radius: 10px;
    height: 2rem;
    width: 100%;
}

.contact-section-container button {
    background: #DFE16C;
    box-shadow: 4px 4px 4px rgba(0, 0, 0, 0.25);
    border-radius: 10px;
    color: black;
    font-size: 1.25rem;
    font-weight: 600;
    width: 10em;
    height: 2.5em;
    /* 新增:按钮左对齐,固定在左下角 */
    justify-self: start;
}

/* 新增:消息输入组垂直排列,让textarea自动拉伸 */
.contact-form-input-container > div:last-of-type {
    display: flex;
    flex-direction: column;
}

textarea {
    resize:none;
    background: #F2F2F2;
    box-shadow: 1px 1px 4px rgba(0, 0, 0, 0.15);
    border-radius: 10px;
    width: 100%;
    /* 新增:占满消息输入组剩余高度 */
    flex: 1;
    height: auto;
}

/* 新增:小屏适配,避免容器溢出 */
@media (max-width: 768px) {
    .contact-section-container {
        width: 90vw;
        min-width: unset;
        padding: 1.5rem;
    }
}

核心逻辑说明

  • 给外层表单容器开启flex垂直布局,输入容器自动占满标题外的所有可用高度
  • 输入容器用Grid划分为4行:前两行(姓名、邮箱输入组)高度由内容自动适配,第三行(消息输入组)占满剩余所有空间,第四行(按钮)高度由内容自动适配
  • 消息输入组开启flex垂直布局,textarea设置flex:1自动拉伸占满label外的高度
  • 按钮设置justify-self: start实现左对齐,固定在容器左下角
  • 新增小屏媒体查询,适配移动端场景不会出现横向溢出

内容的提问来源于stack exchange,提问作者Ethan Partridge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 16:45:04