使用CSS ::after伪元素覆盖元素及子元素的布局问题
解决CSS ::after伪元素被子元素挤压的问题
问题场景
我想用CSS ::after伪元素完全覆盖目标容器,实现鼠标悬停时伪元素通过过渡动画收起,显示下方的.subsect-text子元素。但添加子元素后,伪元素被向下挤压,无法正常覆盖容器;没有子元素时功能正常。另外需要保留.subsect-text的inline显示效果。
解决方案
核心是让伪元素脱离文档流,避免被子元素挤占空间,同时确保容器作为定位参考:
- 给所有
[class^='container__subsect']元素添加position: relative,为伪元素提供定位基准 - 给
::after伪元素添加position: absolute、top: 0、left: 0,使其脱离文档流并完全覆盖父容器 - 给
.subsect-text添加适当内边距,优化文本显示效果
修改后的代码
CSS
[class^="sect__"] { display: flex; justify-content: space-between; width: 100%; height: 80vh; border: 1px solid black; margin-bottom: 20vh; } [class^='container__subsect']{ border: 1px solid black; width: calc(100%/3); position: relative; /* 添加定位基准 */ overflow: hidden; /* 确保伪元素收起时内容不溢出 */ } [class^='container__subsect']::after{ font-size: 4rem; display: flex; align-items: center; justify-content: center; height: 100%; width: 100%; background-color: #fff; overflow-y: hidden; transition: all 0.3s; position: absolute; /* 脱离文档流 */ top: 0; left: 0; } .container__subsect-1::after{ content: "Networking"; } .container__subsect-2::after{ content: "JavaScript"; } .container__subsect-3::after{ content: "Endpoint Management"; } [class^='container__subsect']:hover::after{ height: 0%; content: ""; } .subsect-text { text-align: left; font-size: 2rem; display: inline; padding: 1rem; /* 添加内边距优化显示 */ }
HTML(无需修改)
<section class="sect__1"> <div class="container__subsect-1"> <div class="subsect-text"> Networking with meraki is a way of using cloud-based technology to manage and monitor networks of devices, such as routers, switches, cameras, and access points. Meraki provides a dashboard that allows users to configure, troubleshoot, and secure their networks from anywhere. </div> </div> <div class="container__subsect-2"> <div class="subsect-text"> Javascript is a programming language that runs in web browsers and enables dynamic and interactive web pages. Javascript can also be used for server-side development, mobile applications, desktop applications, and game development. Javascript is one of the most popular and widely used languages in the world. </div> </div> <div class="container__subsect-3"> <div class="subsect-text"> Endpoint management is the process of securing and maintaining the devices that connect to a network, such as laptops, smartphones, tablets, and printers. Endpoint management involves installing software updates, enforcing security policies, detecting and resolving threats, and providing remote support. </div> </div> </section>
内容的提问来源于stack exchange,提问作者Daikyu
相关产品推荐
相关产品推荐

