如何让div紧邻textarea?附代码及flexbox尝试失败说明
实现textarea与指定div横向紧邻布局的解决方案
需求:让.code-runner元素紧邻<textarea>横向排列,当前div位于textarea下方,未实现相邻布局。
修改思路
核心是通过Flexbox布局将两个元素包裹在同一个容器中,利用flex的横向排列特性实现紧邻效果,同时修正原代码中的一些不合理写法。
修改后的完整代码
HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>.HUS LENGUAGE</title> <link rel="stylesheet" href="hus.css"> </head> <body> <div class="initial-bar" style="background-color: #1a1a1a; width: 1330px; height: 90px;"> <div class="text-title-spacing"> </div> <h1 class="p-title-bar"> .HUS</h1> <div class="go-button"> <p id="button-title"> RUN !</p> </div> </div> <p id="spacer"></p> <!-- 新增flex容器包裹textarea和code-runner --> <div class="content-container"> <textarea></textarea> <div class="code-runner"></div> </div> </body> </html>
CSS代码
body { background: #2a2a2a; color: white; font-family: sans-serif; margin: 0; padding: 0; } .p-title-bar { color: white; font-size: 32px; line-height: 18px; font-style: oblique; display:inline-block; } .go-button { background-color: #207000; border-radius: 10px; width: 100px; height: 50px; display:inline-block; margin-left: 20px; /* 替换原有的多个 ,更规范 */ } #button-title { font-size: 18px; line-height: 18px; } /* 新增flex容器样式 */ .content-container { display: flex; gap: 15px; /* 控制两个元素之间的间距 */ align-items: flex-start; /* 顶部对齐 */ padding: 0 10px; } textarea { background-color: #1a1a1a; width: 675px; height: 675px; border: none; /* 原border写法错误,改为none */ color: white; line-height: 1.5; /* 原逗号改为点,是正确的写法 */ font-size: 25px; resize: none; /* 可选:禁止textarea拉伸 */ } .code-runner { width: 645px; height: 675px; /* 和textarea高度统一,视觉更协调 */ background-color: #1a1a1a; border: none; } #spacer { height: 20px; /* 给spacer设置高度,代替空标签的占位 */ margin: 0; }
关键修改点说明
- 新增
content-container容器,设置display: flex实现横向排列,通过gap控制元素间距,align-items: flex-start保证顶部对齐 - 将原代码中错误放置在
<body>内的<link>标签移到<head>中,符合HTML规范 - 修正
line-height: 1,5为line-height: 1.5,逗号是CSS语法错误 - 把
.go-button前的多个 替换为margin-left,样式维护更便捷 - 给
#spacer设置具体高度,替代空p标签的占位方式 - 统一
.code-runner与textarea的高度,保证视觉上的协调对齐
内容的提问来源于stack exchange,提问作者Yndira Hernandez
相关产品推荐
相关产品推荐

