首页 > 解决方案 > 伪元素可以充当块元素而不重叠吗?

问题描述

div我有三个 50x50 的彩色块,内容为 R、G 和 B。如果它们是三个彼此相邻的元素,这些块是否可以像预期的那样垂直排列?

在此处输入图像描述

如果使用与红色块相同高度的边距底部是可能的,但前提是红色块不包含任何文本。这是因为文本的高度被添加到边距的高度。

有没有办法只用 , 和 来完成.red这项.red::after工作.blue

body {
   width: 100%;
   height: 80vh;
   display: flex;
   align-items: center;
   justify-content: center;
}

.demo-container {
   display: flex;
   align-items: center;
   justify-content: center;
   padding: 24px;
   border: solid 1px #d5d9dc;
}

.red {
   background: pink;
   display: block;
   min-width: 50px;
   height: 50px;
   position: relative;
}

.red::after {
   content: "G";
   background-color: rgba(64, 255, 64, 0.5);
   display: block;
   min-width: 50px;
   height: 50px;
   position: relative;
}

.blue {
   background-color: rgba(64, 64, 255, 0.5);
   display: block;
   min-width: 50px;
   height: 50px;
   position: relative;
}
<!DOCTYPE html>

<div class="demo-container">
   <div class="container">
      <div class="red">R</div>
      <div class="blue">B</div>
   </div>
   <br/>
</div>

标签: htmlcss

解决方案


您可以添加position: relative;height: 100px.red元素。

然后添加:position: absolute; bottom: 0;.red:after元素

body {
   width: 100%;
   height: 80vh;
   display: flex;
   align-items: center;
   justify-content: center;
}

.demo-container {
   display: flex;
   align-items: center;
   justify-content: center;
   padding: 24px;
   border: solid 1px #d5d9dc;
}

.red {
   background: pink;
   display: block;
   min-width: 50px;
   height: 100px;
   position: relative;
}

.red::after {
   content: "G";
   background-color: rgba(64, 255, 64, 0.5);
   display: block;
   min-width: 50px;
   height: 50px;
   position: absolute;
   bottom: 0
}

.blue {
   background-color: rgba(64, 64, 255, 0.5);
   display: block;
   min-width: 50px;
   height: 50px;
   position: relative;
}
<!DOCTYPE html>

<div class="demo-container">
   <div class="container">
      <div class="red">R</div>
      <div class="blue">B</div>
   </div>
   <br/>
</div>


推荐阅读