如何实现文本与双引号对齐?尝试定位后文本无法居中
解决文本与引号对齐且保持居中的问题
你可以通过相对+绝对定位实现引号的定位,同时确保文本始终居中,不会被引号干扰。核心思路是把p元素设为相对定位容器,将前后引号伪元素绝对定位到容器对应角落,同时调整内边距避免文本和引号重叠。
修改后的完整代码如下:
CSS代码
p{ max-width: 1200px; background: #135527; border: 7px solid #135527; border-radius: 56px; width: 40%; font-family: 'Nunito Sans'; font-style: normal; font-weight: 900; font-size: 32px; line-height: 44px; text-align: center; padding: 40px 60px; /* 增加左右内边距,给引号留出空间 */ margin: 30px auto; color: #FFFFFF; position: relative; /* 设置为相对定位,作为伪元素的定位基准 */ } p::before { content: open-quote; font-family: 'Amarante'; font-style: normal; font-weight: 400; font-size: 85px; color: #FFFFFF; position: absolute; top: 10px; /* 调整顶部位置,和文本对齐 */ left: 20px; /* 调整左侧位置 */ } p::after { content: "\201E"; font-family: 'Amarante'; font-style: normal; font-weight: 400; font-size: 85px; color: #FFFFFF; position: absolute; bottom: 10px; /* 调整底部位置,和文本对齐 */ right: 20px; /* 调整右侧位置 */ }
HTML代码
<p>Healthy living is making yourself feel at home by creating a home where your body & mind thrive.</p>
关键修改点:
- 给p添加
position: relative,让伪元素可以基于它定位 - 调整p的
padding,增加左右内边距,防止文本和引号重叠 - 给两个伪元素设置
position: absolute,用top/left和bottom/right精准控制引号位置,替代原来的padding - 文本的
text-align: center不会受到引号影响,始终保持居中对齐
你可以根据实际需求微调top/left/bottom/right的数值,让引号和文本的对齐效果更贴合目标样式。
内容的提问来源于stack exchange,提问作者Mel Mendonca
相关产品推荐
相关产品推荐

