如何在HTML/CSS中将按钮放置在<pre>元素下方?
按钮布局问题求助
我希望将按钮放置成如下效果:
这是我目前的代码,但尝试的方法都无效:
现有CSS代码
#container { text-align : center; } .button { border : none; color : rgba(93, 24, 172, 0.603); padding : 15px 15px; text-align : center; text-decoration : none; display : inline-block; font-size : 10px; margin : 10px 2px; cursor : pointer; position : absolute; } .button1 { background-color : white; } /* added to see white text */ body { background : darkblue; }
现有HTML代码
<pre style="font-family:Calibri; color:white;text-align:left;"> Duis aute irure dolor in reprehenderit in voluptare velit esse cillum dolore eu fugiat nulla pariatur. Exceptur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est. </pre> <div text-align="center"> <button class="button button1" style="text-align:right;">READ MORE</button> </div>
请问我哪里出错了?欢迎提供帮助,谢谢!
问题分析与修正方案
你的代码存在几个关键问题:
- 按钮设置了
position: absolute:这个属性会让按钮脱离正常文档流,无法和上方文本块保持布局关联,自然没法对齐到文本块的右下角。 - 按钮容器的
text-align属性无效:HTML里没有text-align这个原生属性,要设置对齐必须用style="text-align: right;"或者CSS类。 - 文本与按钮无共同父容器:两者是独立的元素,没有统一的布局容器,导致按钮无法相对于文本块定位。
下面是修正后的代码:
修正后的CSS
/* 统一布局的父容器,可按需调整宽度 */ .content-block { width: 80%; margin: 0 auto; } .button { border : none; color : rgba(93, 24, 172, 0.603); padding : 15px 15px; text-align : center; text-decoration : none; display : inline-block; font-size : 10px; margin : 10px 2px 10px 0; cursor : pointer; /* 移除position: absolute,让按钮回到正常文档流 */ } .button1 { background-color : white; } body { background : darkblue; } pre { font-family:Calibri; color:white; text-align:left; margin: 0; /* 清除pre默认margin,让布局更紧凑 */ } /* 按钮容器设置靠右对齐 */ .button-container { text-align: right; }
修正后的HTML
<div class="content-block"> <pre> Duis aute irure dolor in reprehenderit in voluptare velit esse cillum dolore eu fugiat nulla pariatur. Exceptur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est. </pre> <div class="button-container"> <button class="button button1">READ MORE</button> </div> </div>
修正说明
- 移除按钮的
position: absolute,让它回到正常文档流中; - 新增
content-block父容器,将文本和按钮纳入其中,统一控制宽度与整体布局; - 给按钮容器设置
text-align: right,让按钮自动对齐到父容器右侧,与上方文本块的右边缘保持一致; - 清除
pre的默认margin,优化布局紧凑度。
内容的提问来源于stack exchange,提问作者anon2001
相关产品推荐
相关产品推荐

