如何将容器元素包裹在内联块子元素周围

How to wrap a container element around inline-block children

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

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

    .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>

Codepen here

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

* {
  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>