首页 > 解决方案 > 使 ::after 元素的大小和位置与 flex 子元素相同

问题描述

我正在尝试按照这篇文章为我的 flex 元素添加一个有效的 box-shadow 。

问题是它不起作用,这是缩小的例子

我试过设置position: relativeon nav,但它只是使::after元素成为整个导航栏的大小。

<nav>
  <div class="nav-left">
    <a href="#">
      hello
    </a>
  </div>
  <div class="nav-center"></div>
  <div class="nav-right"></div>
</nav>
nav {
  display: flex;
  min-height: 5rem;
  background-color: #402424;
  align-items: stretch;
}

nav a,
nav .brand {
  text-decoration: none;
  align-items: center;
  display: flex;
  color: #AFAFAF;
}

nav a::after {
  content: '';
  position: absolute;
  z-index: -1;
  width: 100%;
  height: 100%;
  opacity: 0;
  border-radius: 5px;
  box-shadow: 0 5px 15px rgba(0,0,0,0.3);
  transition: opacity 0.3s ease-in-out;
}

nav a:hover::after {
  opacity: 1;
}

标签: css

解决方案


试试这个,

添加到导航

nav a{position:relative;}

还添加到导航 a::after

nav a::after{
  top:0;
  right:0;
  left:0;
  bottom:0;
}

body {
  background: #20262E;
  padding: 0;
  margin: 0;
  font-family: Helvetica;
}

nav {
  display: flex;
  min-height: 5rem;
  background-color: #402424;
  align-items: stretch;
}

nav a,
nav .brand {
  text-decoration: none;
  align-items: center;
  display: flex;
  color: #AFAFAF;
  position:relative;
}

nav a::after {
  content: '';
  position: absolute;
  z-index: 1;
  opacity: 0;
  top:0;
  right:0;
  left:0;
  bottom:0;
  border-radius: 5px;
  box-shadow: 0 5px 15px rgba(0,0,0,0.3);
  transition: opacity 0.3s ease-in-out;
}

nav a:hover::after {
  opacity: 1;
}
.nav-left,
.nav-center,
.nav-right {
  display: flex;
  flex: 1;
}

.nav-left {
  justify-content: flex-start;
}

.nav-center {
  justify-content: center;
}

.nav-right {
  justify-content: flex-end;
}
<nav>
  <div class="nav-left">
    <a href="#">
      hello
    </a>
  </div>
  <div class="nav-center">
  
  </div>
  <div class="nav-right">
    World
  </div>
</nav>


推荐阅读