【问题标题】:Set width of the right div based on left div [duplicate]根据左div设置右div的宽度[重复]
【发布时间】:2019-08-16 23:50:59
【问题描述】:

我有一个标记,其中我有一个容器,可以说宽度为 100%,并且我在这个容器中有两个子元素。第一个子元素的宽度基于此 div 内的文本,然后下一个 div 应具有(容器宽度的宽度)-(第一个子元素)。

请看下图说明:

在这种情况下,白色框的宽度为 100%,宽度取决于其文本内容。绿色 div 应具有(白框宽度)-(红框宽度)。

如何在 CSS 中设置绿色宽度?这是我迄今为止尝试过的:

.ContentItemMenu {
  width: 100%;
  height: 50px;
  /* background-color: bisque; */
  border-bottom: 1px solid #c3c3c3;
}

.ContentTitle {
  width: auto;
  padding: 0 20px;
  height: 100%;
  float: left;
  font-size: 25px;
  font-family: opensansBold;
  text-align: left;
  line-height: 50px;
  background-color: #5144F0;
}

.SubContentTabs {
  width: 100%;
  height: 100%;
  float: left;
  background-color: aquamarine;
}
<div class="ContentItemMenu">
  <div class="ContentTitle">Some text</div>
  <div class="SubContentTabs"></div>
</div>

我是一个完整的 CSS 新手,所以如果需要更多说明,请告诉我。

【问题讨论】:

    标签: html css dynamic width


    【解决方案1】:

    使用 flexbox - 将 display: flex 添加到 ContentItemMenu 并将 flex: 1 设置为 SubContentTabs - 请参见下面的演示:

    .ContentItemMenu {
      display: flex; /* ADDED */
      width: 100%;
      height: 50px;
      /* background-color: bisque; */
      border-bottom: 1px solid #c3c3c3;
    }
    
    .ContentTitle {
      width: auto;
      padding: 0 20px;
      height: 100%;
      float: left;
      font-size: 25px;
      font-family: opensansBold;
      text-align: left;
      line-height: 50px;
      background-color: #5144F0;
    }
    
    .SubContentTabs {
      width: 100%;
      height: 100%;
      float: left;
      background-color: aquamarine;
      flex: 1; /* ADDED */
    }
    <div class="ContentItemMenu">
      <div class="ContentTitle">Some text</div>
      <div class="SubContentTabs"></div>
    </div>
    <br/>
    <div class="ContentItemMenu">
      <div class="ContentTitle">Some text here, this is a long text</div>
      <div class="SubContentTabs"></div>
    </div>

    【讨论】:

    • 太棒了,所有浏览器都支持这种技术吗?
    • 如果您必须支持非常旧的浏览器(或电子邮件客户端),您可以随时使用表格。
    • 不需要很旧 :) 谢谢!
    • 在所有 现代浏览器(IE11+、Chrome 和 Firefox)中,我想当你了解更多关于 CSS 的知识时,你会肯定偶然发现 flexbox: )
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    • 2021-11-16
    相关资源
    最近更新 更多