【发布时间】:2019-01-02 06:23:01
【问题描述】:
如何将弹性容器的子元素的绝对定位居中?
容器已经设置为justify-content:center,但是由于孩子是绝对定位的,这不会影响它并且它不会居中。
徽标(手头的问题是徽标)被“绝对定位”以能够应用 z-index,因此我可以让它可点击(在它会在几个层之间丢失之前我不会'看不到或无法单击它)。
我附上图片来解释我的观点(请耐心等待,因为我无法嵌入图片 - 没有足够的 stackoverflow 业力)。相关代码如下。
- Situation now, the logo doesn't center above the navigation menu, on mobile
- All ok on desktop, given on large screens I'm forcing a
float: leftto implement the design - The intended result (I've manipulated the screenshot to show the intended final result). How to achieve this?
这是我尝试过的:
- 玩过 flex box 居中,直到我意识到这不适用于绝对定位的子元素
- 已使用,
display: block;margin-left: auto;margin-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;
}
}
【问题讨论】:
-
只需在移动设备上使用媒体查询和徽标
inner-masthead更改position:relative和text-align: center。甚至不需要媒体查询,我只是在您的网页上尝试过,将绝对值更改为相对值,并添加文本对齐中心,它将起作用:D -
非常感谢@Goku,应用了
position:relative,这有帮助,但text-align: center没有,然后我用display: flex; align-items: center; justify-content: center;将flex child centering 带到了子CSS 并且有效 -
你知道你现在必须做什么了^^^
标签: html css twitter-bootstrap flexbox