如何使用3个position: static的矩形元素实现六角星图案
问题描述
我正在使用CSS实现如下设计效果:
现有一个父级容器包含3个子元素,需要让所有子元素相互重叠,但不允许为3个子元素设置position: absolute;属性,要使用position: static;实现相同的图案。
现有参考代码
CSS代码
.container { width: 370px; height: 370px; margin: calc(50vh - 185px) auto; background-image: radial-gradient(#fff, #fff, #fff, #eee, #ddd, #ccc); } .outer-flower { width: 80px; height: 350px; border: 1px solid #f00; position: absolute; margin: 10px auto; left: 155px; } .outer-flower:nth-child(1){ transform: rotate(0deg); } .outer-flower:nth-child(2){ transform: rotate(120deg); } .outer-flower:nth-child(3){ transform: rotate(240deg); }
HTML代码
<div class="container"> <div class="outer-flower" data-rotate="0"></div> <div class="outer-flower" data-rotate="120"></div> <div class="outer-flower" data-rotate="240"></div> </div>
实现方案
你可以通过给父容器设置Grid布局实现需求,Grid布局下所有子元素默认会堆叠在同一网格区域,不需要修改子元素默认的position: static属性,修改后的CSS代码如下:
.container { width: 370px; height: 370px; margin: calc(50vh - 185px) auto; background-image: radial-gradient(#fff, #fff, #fff, #eee, #ddd, #ccc); /* 新增Grid布局配置 */ display: grid; place-items: center; } .outer-flower { width: 80px; height: 350px; border: 1px solid #f00; /* 删掉原有的position: absolute和left定位属性,子元素保持默认static即可 */ margin: 10px auto; /* 所有子元素占用同一网格区域 */ grid-area: 1/1/-1/-1; } .outer-flower:nth-child(1){ transform: rotate(0deg); } .outer-flower:nth-child(2){ transform: rotate(120deg); } .outer-flower:nth-child(3){ transform: rotate(240deg); }
HTML代码不需要做任何修改,运行后即可得到和原absolute定位完全一致的效果。
内容的提问来源于stack exchange,提问作者Rohit
相关产品推荐
相关产品推荐

