如何在CSS绘制的圆形中实现文本垂直居中?
圆形环绕文本垂直居中的纯CSS解决方案
问题背景
基于示例实现圆形环绕文本后,移除footer和部分文本时发现文本无法垂直居中。尝试过Flex/Table布局、绝对定位等常规方法,都会破坏shape-outside的文本环绕效果,需要纯CSS无JS的解决方案。
解决方案
通过给父容器添加Flex布局实现垂直居中,同时保留原有浮动的shape-outside元素,不会破坏环绕效果。
修改后的完整代码
HTML(已移除footer)
<div class="quote-wrapper"> <blockquote class="text"> <p>Experience design is the design of anything, independent of medium, or across media, with human experience as an explicit outcome, and human engagement as an explicit goal.</p> </blockquote> </div>
CSS(关键修改已标注)
@import url("https://fonts.googleapis.com/css?family=Titillium+Web:400,400i,700&display=swap"); @import url("https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css"); *, *:before, *:after { box-sizing: border-box; } body { font-family: "Titillium Web", sans-serif; font-size: 20px; line-height: 1.4; color: #161b1e; } .quote-wrapper { width: 300px; height: 300px; position: relative; margin: 10vh auto 0; } .text { width: 100%; height: 100%; background: radial-gradient( ellipse at center, rgba(0, 128, 172, 1) 0%, rgba(0, 128, 172, 1) 70%, rgba(0, 128, 172, 0) 70.3% ); position: relative; margin: 0; color: white; /* 新增:用Flex实现垂直居中 */ display: flex; align-items: center; } .text p { /* 修改:移除height:100%,由父容器控制垂直居中 */ height: auto; font-size: 21px; line-height: 1.25; padding: 0; text-align: center; font-style: italic; text-shadow: 0.5px 0.5px 1px rgba(0, 0, 0, 0.3); } .text::before { content: ""; width: 50%; height: 100%; float: left; shape-outside: polygon( 0 0, 98% 0, 50% 6%, 23.4% 17.3%, 6% 32.6%, 0 50%, 6% 65.6%, 23.4% 82.7%, 50% 94%, 98% 100%, 0 100% ); shape-margin: 7%; } .text p::before { content: ""; width: 50%; height: 100%; float: right; shape-outside: polygon( 2% 0%, 100% 0%, 100% 100%, 2% 100%, 50% 94%, 76.6% 82.7%, 94% 65.6%, 100% 50%, 94% 32.6%, 76.6% 17.3%, 50% 6% ); shape-margin: 7%; } .quote-wrapper::before { content: "\201C"; font-size: 270px; height: 82px; line-height: 1; position: absolute; top: -48px; left: 0; z-index: 1; font-family: sans-serif, serif; color: #ccc; opacity: 0.9; } @media (min-width: 850px) { .quote-wrapper { width: 370px; height: 370px; } .quote-wrapper::before { font-size: 300px; } .text p { font-size: 26px; } } /* 非核心样式可保留或移除 */ .note { margin: 5vw; padding: 0.5em; border-left: 0.5em solid #52e052; background: #e9fbe9; } .note a { text-decoration: none; color: #161b1e; } .note a:hover { text-decoration: underline; }
原理说明
Flex容器中的浮动元素依然会正常触发shape-outside的文本环绕逻辑,同时align-items: center可以让内部的p元素垂直居中。之前设置height:100%会让p元素自身占满高度,导致文本在p内部无法居中,改为父容器Flex控制后,文本会自然在圆形区域内垂直居中。
内容的提问来源于stack exchange,提问作者Guesser
相关产品推荐
相关产品推荐

