【问题标题】:How to use css styling that the available width is used in the one column and the other column use width it needs如何使用css样式,在一列中使用可用宽度,另一列使用它需要的宽度
【发布时间】:2019-02-24 19:06:02
【问题描述】:

我需要 2 列的 CSS 样式。第一列应该使用完整的宽度,而它旁边的第二列应该只使用它需要的宽度。我怎样才能做到这一点?有没有办法用 display: flex 做到这一点?

示例:

"-" = 空格

如果第二列是 display: none,第一列应该使用宽度 100%

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

如果不是

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

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

【问题讨论】:

  • 您好,欢迎来到 Stackoverflow。请阅读stackoverflow.com/help/how-to-askstackoverflow.com/help/mcve 并编辑您的问题以符合这些准则。向我们展示您迄今为止所做的尝试。请注意,Stackoverflow 不是编码服务,我们希望您对该主题进行一些研究并尝试解决您的问题。话虽如此,我会研究现有的 CSS 框架,因为它们具有出色的响应式设计和良好的文档。 Bootstrap 就是一个例子。

标签: html css flexbox display


【解决方案1】:

你可以用下面的代码做到这一点:

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

【讨论】:

  • OP 需要display: flex 的解决方案。
【解决方案2】:

你可以用 flexbox 做到这一点。只需将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>

如果隐藏第二个孩子,结果如下:

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

【讨论】:

  • 几乎,因为如果你在你的第二个孩子中写“测试测试测试”,它会打破这条线......我不知道为什么,但基本上它是正确的。嗯,你知道解决方案吗?
  • 是的,只为第二个孩子使用white-space: nowrap;
【解决方案3】:

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

【讨论】:

  • 这不使用父级的全宽。
猜你喜欢
  • 2014-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-04
  • 2011-06-29
  • 1970-01-01
  • 2014-09-24
  • 2015-07-05
相关资源
最近更新 更多