如何将播放图标居中放置在蓝绿色(teal)方块内?
解决方案
要实现将播放图标置于蓝绿色方块中央,只需调整HTML结构和少量CSS:
- 调整HTML结构:把播放图标(
.cover)移入蓝绿色方块(.channel-tile__artwork)内部,让它成为方块的子元素。 - 修改CSS定位:给
.cover设置绝对定位,通过left: 50%+top: 50%+transform: translate(-50%, -50%)实现完美居中;同时确保父元素.channel-tile__artwork设置position: relative作为定位参考容器。
修改后的完整代码
CSS
.channel-tile { -webkit-box-sizing: border-box; box-sizing: border-box; border-radius: 4px; width: 180px; float: left; display: block; margin-bottom: 18px; background: #2E2E2E; position: relative; } .channel-tile__image-area { width: 180px; height: 0; padding-top: 100%; position: relative; z-index: 0; border-radius: 4px; background: red; border: 1px solid blue; } .channel-tile__artwork { position: absolute; left: 0; top: 0; bottom: 0; right: 0; margin: auto; width: 170px; height: 170px; -webkit-box-sizing: border-box; box-sizing: border-box; z-index: 0; background: teal; /* 新增:作为绝对定位子元素的参考容器 */ position: relative; } .cover { -webkit-appearance: none; appearance: none; display: flex; justify-content: center; align-items: center; /* 修改:改为绝对定位,相对于父元素居中 */ position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: 72px; height: 72px; border-radius: 50%; cursor: pointer; border: 9px solid blue; background: transparent; filter: drop-shadow(3px 3px 3px rgba(0, 0, 0, 0.7)); } .cover::before { content: ""; width: 0; height: 0; border-top: 20px solid transparent; border-bottom: 20px solid transparent; border-left: 27px solid blue; transform: translateX(4px); }
HTML
<div class="channel-tile"> <div class="channel-tile__image-area"> <span class="channel-tile__artwork"> <!-- 将cover移入蓝绿色方块内部 --> <div class="cover"></div> </span> </div> </div>
修改后播放图标会精准居中在蓝绿色方块内部,同时保留原有的样式效果。
内容的提问来源于stack exchange,提问作者user17631451
相关产品推荐
相关产品推荐

