【问题标题】:Can a pseudo-element act as a block element without overlap?伪元素可以充当块元素而不重叠吗?
【发布时间】:2021-03-17 19:22:34
【问题描述】:

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

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

有没有办法只使用 .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>

【问题讨论】:

    标签: html css


    【解决方案1】:

    您可以将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>

    【讨论】:

      猜你喜欢
      • 2013-07-25
      • 2012-08-13
      • 2017-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-18
      相关资源
      最近更新 更多