不知道如何沿主轴单独对齐我的弹性项目
Posted
技术标签:
【中文标题】不知道如何沿主轴单独对齐我的弹性项目【英文标题】:Not sure how to align my flex items individually along the main axis 【发布时间】:2020-11-05 06:38:45 【问题描述】:所以,我正在尝试使用 flexbox 创建导航栏,基本上我希望我的徽标居中,导航栏切换器位于屏幕左侧。 但是,如果我为 flex 容器提供值为 center 的 justify-content 属性,它只会使我的徽标和导航栏切换器居中。
我想知道是否有类似于 align-self 属性但用于主轴的东西? 所以我可以将我的徽标设置为居中,将导航栏切换器设置在屏幕左侧?
这是我的 html 代码:
<header class="main-navbar">
<div class="nav-toggler">
<span></span>
<span></span>
<span></span>
</div>
<div class="brand">
<a class="logo-link" href="#">
<img src="imgs/logo/logo-lightgrey.png" >
</a>
</div>
</header>
这是我的css代码:
.main-navbar
position:fixed;
display: flex;
justify-content: center;
align-items: center;
height: 3.5rem;
width: 100%;
font-weight: 500;
.nav-toggler
display: flex;
flex-direction: column;
justify-content: space-between;
height: 1rem;
cursor: pointer;
.nav-toggler span
width: 1.3rem;
height: 0.17rem;
background: white;
display: block;
【问题讨论】:
【参考方案1】:使用 margin-right: auto
推送两个子元素.main-navbar
position:fixed;
display: flex;
justify-content: center;
align-items: center;
height: 3.5rem;
width: 100%;
font-weight: 500;
background-color: #000;
.nav-toggler
display: flex;
flex-direction: column;
justify-content: space-between;
height: 1rem;
cursor: pointer;
.nav-toggler span
width: 1.3rem;
height: 0.17rem;
background: white;
display: block;
/**/
.nav-toggler,
.brand
margin-right: auto;
<header class="main-navbar">
<div class="nav-toggler">
<span></span>
<span></span>
<span></span>
</div>
<div class="brand">
<a class="logo-link" href="#">
<img src="https://www.placehold.it/100x50" >
</a>
</div>
</header>
【讨论】:
虽然,您的解决方案在某种程度上使徽标居中,但并非完全居中。我希望标志正好在中间。【参考方案2】:我不确定是否有针对此的纯弹性解决方案。您可能需要尝试将position: absolute
添加到.nav-toggler
。这将从整个流程中移除切换器,并允许徽标位于不受影响的中心。
.main-navbar
position: fixed;
display: flex;
justify-content: center;
align-items: center;
height: 3.5rem;
width: 100%;
font-weight: 500;
background: black;
.nav-toggler
position: absolute;
left: 0;
display: flex;
flex-direction: column;
justify-content: space-between;
height: 1rem;
cursor: pointer;
margin-left: 1rem;
.nav-toggler span
width: 1.3rem;
height: 0.17rem;
background: white;
display: block;
.brand img
display: block; /* not necessary, just added to vertically align image for demo */
<header class="main-navbar">
<div class="nav-toggler">
<span></span>
<span></span>
<span></span>
</div>
<div class="brand">
<a class="logo-link" href="#">
<img src="https://placeimg.com/150/30/animals" >
</a>
</div>
</header>
【讨论】:
以上是关于不知道如何沿主轴单独对齐我的弹性项目的主要内容,如果未能解决你的问题,请参考以下文章