这是我第一次涉足使用 CSS Flexbox 而不是 float ,就此而言,我的 CSS 有点生疏。我想知道是否有一种方法可以用 flexbox 模仿 margin: 0 auto
。
我知道 align-items: center;
和 justify-content: center;
会正常工作,但在我的例子中,我有一个 800px 的导航部分,我总是希望位于浏览器窗口的中心(使用 align-items: center
很容易)。
问题是我在导航部分之后有一个背景渐变,我想显示它同时保持导航在屏幕上居中。我尝试了以下 CSS 的变体,但只能让第二个代码块起作用。
nav {
flex: 0 0 55em;
height: inherit;
margin: 0;
padding: 0;
background-image: url("/images/assets/gradientRL.png");
background-position: right;
background-repeat: no-repeat;
}
nav::before, nav::after {
content: "";
flex: 1 1;
}
nav::after{
background-image: url("/images/assets/gradientLR.png");
background-position: left;
background-repeat: no-repeat;
}
下面的作品使用两个 div 将字体颜色设置为透明,但我希望有更好的解决方案。提前致谢 - CES
nav:first-of-type {
flex: 0 0 55em;
height: inherit;
margin: 0;
padding: 0;
text-align: right;
background-image: url("/images/assets/gradientRL.png");
background-position: right;
background-repeat: no-repeat;
}
.one,
.two {
flex: 1 1;
color: transparent;
}
.two {
background-image: url("/images/assets/gradientLR.png");
background-position: left;
background-repeat: no-repeat;
background-color: yellow;
}
<header role="banner">
<div class="one">x</div>
<nav class="nav">
hello
</nav>
<div class="two">x</div>
</header>
最佳答案
您可以在 header
上使用伪元素而不是额外的 div
来实现这一点。
在这里,我将 header
设为 flex 行容器,并赋予了伪 flex: 1
。
这将使伪共享剩余空间,并将 nav
推到中间。
堆栈片段
nav {
width: 100px;
background: lightgray;
}
header {
display: flex;
}
header::before, header::after {
content: ' ';
flex: 1;
}
header::after {
background-image: url("http://images.evansante.com/grides/gradientLR.png");
background-position: left;
background-repeat: no-repeat;
background-color: yellow;
}
<header role="banner">
<nav class="nav">
hello
</nav>
</header>
请注意,您可以保留您的 div
,而无需使用透明字体的任何技巧。
堆栈片段
nav {
width: 100px;
background: lightgray;
}
header {
display: flex;
}
header div:first-child, header div:last-child {
flex: 1;
}
header div:last-child {
background-image: url("http://images.evansante.com/grides/gradientLR.png");
background-position: left;
background-repeat: no-repeat;
background-color: yellow;
}
<header role="banner">
<div></div>
<nav class="nav">
hello
</nav>
<div></div>
</header>
关于CSS Flex Box - 有没有办法使用::Before::After 自动对齐中心,这样你就可以添加内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47982375/