如何使用Flexbox实现一个元素左对齐、另一元素水平居中?
问题原因
Flex布局中,justify-self 仅在交叉轴方向生效,主轴方向的对齐控制由容器的justify-content统一管理,单独给子元素设置justify-self不会起作用。
解决方案
方案1:无需修改HTML结构(推荐)
通过绝对定位实现Logo相对于容器水平居中,同时保留按钮的左对齐效果,仅调整CSS即可:
.menu { width: 39.3rem; height: 4.8rem; background-color: rgba(0, 0, 0, 0.19); display: flex; align-items: center; padding: 0 2.15rem; position: fixed; z-index: 1; } .menu__button{ background: none; border-style: none; } .menu__button-icon{ width: 2.7rem; } .menu__logo{ width: 15.7rem; /* 移除原有margin-left: auto,新增以下属性 */ position: absolute; left: 50%; transform: translateX(-50%); margin: 0; /* 清除figure标签默认外边距 */ } .menu__logo-img{ width: 100%; }
方案2:不使用定位实现
修改HTML结构,在容器右侧新增和按钮宽度一致的占位元素,配合justify-content: space-between实现效果:
<div class="menu"> <button class="menu__button" id="menu__button"> <img class="menu__button-icon" src="./images/burger_menu.svg" alt="menu" /> </button> <figure class="menu__logo"> <img class="menu__logo-img" src="./images/logo.svg" alt="logo" /> </figure> <!-- 新增占位元素,宽度和按钮一致 --> <div class="menu__placeholder" style="width:2.7rem"></div> </div>
.menu { width: 39.3rem; height: 4.8rem; background-color: rgba(0, 0, 0, 0.19); display: flex; align-items: center; justify-content: space-between; /* 新增 */ padding: 0 2.15rem; position: fixed; z-index: 1; } .menu__button{ background: none; border-style: none; } .menu__button-icon{ width: 2.7rem; } .menu__logo{ width: 15.7rem; margin: 0; } .menu__logo-img{ width: 100%; }
内容的提问来源于stack exchange,提问作者roguesquid
相关产品推荐
相关产品推荐

