如何使用 css 样式,一列使用可用宽度,另一列使用它需要的宽度

How to use css styling that the available width is used in the one column and the other column use width it needs

我需要 css 2 列的样式。第一列应该使用完整的宽度,第二列应该只使用它需要的宽度。我怎样才能做到这一点?有什么办法可以用 display: flex?

示例:

"-" = 空格

如果显示第二列:none,第一列应使用宽度 100%

[First-Column-------------------------------------------------------]

如果没有

[First-Column------------------------------------------------][HELLO]

[First-Column-------------------------------------------][HELLOHELLO]

.main{
  display:flex;
}
<div class="main">
  <div>[First-Column------------------------------------------------]</div>
  <div> [HELLO]</div>
</div>

你可以用 flexbox 做到这一点。只需对第一个 child 使用 flex: 1,对第二个使用 flex: 0

.wrapper {
  display: flex;
  flex-flow: row wrap;
  color: white;
}

.child1 {
  flex: 1;
  background: red;
}

.child2 {
  flex: 0;
  background: blue;
}
<div class="wrapper">
  <div class="child child1">
    test
  </div>
  <div class="child child2">
    test
  </div>
</div>

如果隐藏第二个child,结果如下:

.wrapper {
  display: flex;
  flex-flow: row wrap;
  color: white;
}

.child1 {
  flex: 1;
  background: red;
}

.child2 {
  flex: 0;
  background: blue;
  display: none;
}
<div class="wrapper">
  <div class="child child1">
    test
  </div>
  <div class="child child2">
    test
  </div>
</div>


如果你想要只有内容宽度的项目,你可以使用这个:

.wrapper {
  display: flex;
  flex-flow: row wrap;
  color: white;
  justify-content: space-between;
}

.child1 {
  background: red;
}

.child2 {
  background: blue;
}
<div class="wrapper">
  <div class="child child1">
    test
  </div>
  <div class="child child2">
    test
  </div>
</div>

您可以使用以下代码执行此操作:

.mainDiv, .mainDiv div{
  display: block;
}
.mainDiv .firstDiv{
  float: left;
  width: 200px;
}
.mainDiv .secondDiv{
  float: left;
  width: calc(100% - 200px);
}
<div class="mainDiv">
  <div class="firstDiv"> First Div </div>
  <div class="secondDiv"> Second Div </div>
</div>