CSS 父元素没有设置高度,子元素如何跟父元素保持一样的高度?

发布时间 2023-07-10 21:26:12作者: Himmelbleu

宽度有,但是高度没有

如上图所示,height 属性需要让父元素有高度,所以,h2 的 ::before 设置了百分比高度就行不通。样式如下所示:

h2 {

  &::before {
    content: "";
    display: inline-block;
    width: 0.5rem;
    height: 100%;
    border-top-right-radius: 0.5rem;
    border-bottom-left-radius: 0.5rem;
    background-color: var(--text-primary);
  }
}

可以让父元素的定位为相对定位,子元素使用绝对定位,并设置子元素 left: 0bottom: 0,这样就可以让子元素和父元素的高度保持一致了。具体如下所示:

h2 {
  position: relative;

  &::before {
    content: "";
    display: inline-block;
    position: absolute;
    left: 0;
    bottom: 0;
    width: 0.5rem;
    height: 100%;
    border-top-right-radius: 0.5rem;
    border-bottom-left-radius: 0.5rem;
    background-color: var(--text-primary);
  }
}

通过定位让子元素和父元素高度保持一致