首页 > 解决方案 > 如何将容器元素包裹在内联块子项周围

问题描述

我有一个围绕两个内联块元素的容器。但是容器会塌陷(水平虚线)。如何阻止它折叠,以便我可以将背景颜色应用于容器。结构很重要,我想避免使用 flex-box。两个彩色方块右对齐并彼此相邻也很重要。

目的是在画布元素上创建一个绝对定位的块元素。左侧有一个描述性名称,右侧有两个按钮。我必须使用现有的东西,所以一个涉及尽可能少的变化的解决方案会很棒。

    .header3 {
      width: 300px;
      background-color: lightgray;
      border: 1px dashed grey;
      position:relative;
      
    }
    
    .title3{
      position:absolute;
      top:0px;
      left:0px;
      display:inline-block;
      vertical-align:center;
      background-color:#bada55;
    }
    
    .list {
      list-style:none;
      margin:0px;
      padding:0px;
      border:1px dashed green;
      position:absolute;
      display:inline-block;
      top:0px;
      right:0px; 
    }
    
    .item {
      width: 50px;
      height: 50px;
      display: inline-block;
      text-align: center;
    }
    
    .item-1 {
      background-color: orangered;
    }
    
    .item-2 {
      background-color: skyblue;
    }
    <body>
      <br>
      <div class="header3">
        <div class="title3">bollard name</div>
        <ul class="list">
          <li class="item item-1"></li>
          <li class="item item-2"></li>
        </ul>
      </div>
    </body>

这里写代码

标签: htmlcsslayoutinlinecollapse

解决方案


发生这种情况是因为您绝对定位了 .title3 和 .list 元素,从而将它们从正常流程中移除。如果您想在您的上实现此布局float:right并在您的::after div 中ul插入 a )cleardiv (in the code below I achieved this using the:pseudo element of your

* {
  font-family: "Helvetica";
}

/* list */

.header3 {
  width: 300px;
  background-color: lightgray;
  border: 1px dashed grey;
  position:relative;

}

.header3::after {
  content: '';
  display: table;
  clear: both;
}

.title3{
  display:inline-block;
  vertical-align:center;
  background-color:#bada55;
}

.list {
  list-style:none;
  margin:0px;
  padding:0px;
  border:1px dashed green;
  float: right;
}

.item {
  width: 50px;
  height: 50px;
  display: inline-block;
  text-align: center;
}

.item-1 {
  background-color: orangered;
}

.item-2 {
  background-color: skyblue;
}
<div class="header3">
    <div class="title3">bollard name</div>
    <ul class="list">
      <li class="item item-1"></li>
      <li class="item item-2"></li>
    </ul>
  </div>


推荐阅读