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

如何实现按钮始终响应元素,保持在两个textarea正中间?

问题描述

我刚接触CSS,可能这个问题已经有解答了,但我不知道该搜什么关键词。我想让黄色按钮始终位于两个textarea的正中间,但调整窗口大小时,按钮会偏左或偏右,显示效果很差。我目前的代码如下:

HTML代码

<main>
    <div class="container">
        <div class="input1Container">
            <textarea class="input1"></textarea>
        </div>
        <button class="btn"></button>
        <div class="input2Container">
            <textarea class="input2"></textarea>
        </div>
    </div>
</main>

CSS代码

* {
box-sizing: border-box;
margin: 0;
padding: 0;
}

textarea {
border: 1px solid black;
resize: none;
height: 50vh;
}

.input1, .input2{
width: 100%;
}

.container {
display: flex;
column-gap: 10px;
width: 100%;
height: 50vh;
align-items: center;
}

.btn {
background-color: yellow;
border: none;
width: 5rem;
height: 5rem;
border-radius: 100%;
z-index: 90;
position: absolute;
left: 46%;
top: 15rem;
}

.input1Container, 
.input2Container{;
width: 50%;
}
解决方案

你当前的问题在于用position: absolute配合固定的left和top值定位按钮,这种方式无法自适应窗口尺寸变化。利用flex布局的特性就能轻松实现按钮始终居中的效果,修改后的CSS代码如下:

* {
box-sizing: border-box;
margin: 0;
padding: 0;
}

textarea {
border: 1px solid black;
resize: none;
height: 50vh;
}

.input1, .input2{
width: 100%;
}

.container {
display: flex;
column-gap: 10px;
width: 100%;
height: 50vh;
align-items: center;
}

.btn {
background-color: yellow;
border: none;
width: 5rem;
height: 5rem;
border-radius: 100%;
z-index: 90;
/* 移除绝对定位相关属性 */
}

.input1Container, 
.input2Container{
/* 用flex:1代替固定宽度,让两个容器平分可用空间 */
flex: 1;
}

关键修改说明

  1. 移除按钮的绝对定位:绝对定位脱离文档流,无法跟随flex容器的布局变化,所以删掉position: absolute、left、top属性。
  2. 设置输入容器为flex:1:让两个.inputContainer平分容器的可用空间,中间的按钮会自动处于两个textarea的正中间,无论窗口如何调整尺寸,都会保持居中状态。
  3. 清理多余语法:移除.input1Container样式中多余的分号,避免潜在语法问题。

内容的提问来源于stack exchange,提问作者media.queeries

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 20:24:30