由于flex容器的绝对定位子对象不参与flex布局,如何将元素居中



如何将flex容器的子级元素居中放置?

容器已设置为justify-content:center,但由于子对象已完全定位,因此不会影响它,也不会居中。

徽标(眼前的问题是徽标(被"绝对定位"为能够应用z索引,所以我可以让它可以点击(在它在几个层中丢失之前,我看不到它,也无法点击它(。

我附上图片来解释我的观点(请耐心等待,因为我不能嵌入图片——没有足够的堆叠因果关系(。下面的相关代码。

  • 现在的情况是,在移动设备上,徽标不在导航菜单上方
  • 在桌面上一切正常,在大屏幕上我正在强制使用float: left来实现设计
  • 预期结果(我已经操纵了屏幕截图来显示预期的最终结果(。如何做到这一点

这就是我尝试过的:

  • 一直在玩柔框居中,直到我意识到这对绝对定位的子元素不起作用
  • 已使用,display: blockmargin-left: automargin-right: auto;但这没什么区别

如何将徽标置于移动视图导航栏上方的中心位置?请放心,我是个初学者:-(

相关HTML:

<header class="masthead__navigation mb-auto d-flex w-100 p-3 mx-auto flex-column">
<div class="inner">
<a class="inner-masthead" href="#"><img src="assets/images/logo.jpg" style="max-height:40px; width:auto;"></a>
<nav class="nav nav-masthead justify-content-center">
<a class="nav-link active" href="#">Home</a>
<a class="nav-link" href="#">Blog</a>
<a class="nav-link" href="#">Join Newsletter</a>
<a class="nav-link" href="#">Contact</a>
</nav>
</div>
</header>

相关CSS:

@media (min-width:768px) {
.masthead__navigation {
padding-right: 2.5rem !important;
padding-left: 4rem !important
}
.nav-masthead .nav-link {
color: #262626 !important;
color: rgba(26, 26, 26, .5) !important;
}
.nav-masthead .nav-link:hover,
.nav-masthead .nav-link:focus {
border-bottom-color: rgba(26, 26, 26, .5) !important;
}
.nav-masthead .active {
color: #000 !important;
border-bottom-color: #000 !important;
}
}
.masthead__navigation {
margin-bottom: 2rem;
padding-bottom: 0 !important;
width: 100vw !important;
position: absolute !important
}
.inner-masthead {
margin-bottom: 0;
position: absolute !important;
display: block;
margin-left: auto;
margin-right: auto;
z-index: 4 !important
}
.nav-masthead .nav-link {
padding: .25rem 0;
font-weight: 700;
color: #999;
color: rgba(255, 255, 255, .5);
background-color: transparent;
border-bottom: .25rem solid transparent;
z-index: 4 !important
}
.nav-masthead .nav-link:hover,
.nav-masthead .nav-link:focus {
border-bottom-color: rgba(255, 255, 255, .5);
}
.nav-masthead .nav-link + .nav-link {
margin-left: 1rem;
}
.nav-masthead .active {
color: #fff;
border-bottom-color: #fff;
}
@media (min-width: 48em) {
.inner-masthead {
float: left;
}
.nav-masthead {
float: right;
}
}

对于已定位的长方体(即具有除静态以外的任何位置的长方体(,z-index属性指定:1( 当前堆栈上下文中长方体的堆栈级别。2( 框是否建立本地堆叠上下文。

根据MDN-z索引,z索引适用于每个位置不是静态的元素。也许你应该用position:relative或类似的方法来尝试一下,因为它不会将元素从其父元素中射出。

最新更新