Flex表标题尊重内容的宽度

时间:2019-04-24 08:45:51

标签: html css css3 flexbox

当前所有列的宽度相同。我希望带有“ X”内容的第一列缩小到其内部内容的宽度,但不对其宽度进行硬编码。

为空的标题列也应注意内容的宽度。

.table__row{
  display: flex;
}

.table__column {
  border: 1px solid blue;
  display: flex;
  flex-basis: 0;
  flex-grow: 1;
  align-items: center;
  justify-content: center;
  max-width: 100%;
  padding: 12px;
  overflow: hidden;
  text-align: center;
}
<div class="table">
  
  <div class="table__row -header">
    <div class="table__column"></div>
    <div class="table__column">Day</div>
    <div class="table__column">Time</div>
  </div>
  
  <div class="table__row">
    <div class="table__column">
      <a href="#">X</a>
    </div>
    <div class="table__column">Monday</div>
    <div class="table__column">12:00</div>
  </div>
  
  <div class="table__row">
    <div class="table__column">
      <a href="#">X</a>
    </div>
    <div class="table__column">Tuesday</div>
    <div class="table__column">13:20</div>
  </div>
  
  
</div>

2 个答案:

答案 0 :(得分:3)

这应该有效。基本上,您需要为该“列”中的元素将flex-grow设置为0。

.table__row{
  display: flex;
}

.table__column {
  border: 1px solid blue;
  display: flex;
  flex-basis: 0;
  flex-grow: 1;
  align-items: center;
  justify-content: center;
  max-width: 100%;
  padding: 12px;
  overflow: hidden;
  text-align: center;
}

.shrink {
  flex-grow: 0;
}
<div class="table">
  
  <div class="table__row -header">
    <div class="shrink table__column"></div>
    <div class="table__column">Day</div>
    <div class="table__column">Time</div>
  </div>
  
  <div class="table__row">
    <div class="shrink table__column">
      <a href="#">X</a>
    </div>
    <div class="table__column">Monday</div>
    <div class="table__column">12:00</div>
  </div>
  
  <div class="table__row">
    <div class="shrink table__column">
      <a href="#">X</a>
    </div>
    <div class="table__column">Tuesday</div>
    <div class="table__column">13:20</div>
  </div>
  
  
</div>

答案 1 :(得分:0)

应用此CSS

.-header .table__column:first-child{
  display: contents;
}

<div class="table">

  <div class="table__row -header">
    <div class=" table__column"></div>
    <div class="table__column">Day</div>
    <div class="table__column">Time</div>
  </div>

  <div class="table__row">
    <div class="shrink table__column">
      <a href="#">X</a>
    </div>
    <div class="table__column">Monday</div>
    <div class="table__column">12:00</div>
  </div>

  <div class="table__row">
    <div class="shrink table__column">
      <a href="#">X</a>
    </div>
    <div class="table__column">Tuesday</div>
    <div class="table__column">13:20</div>
  </div>


</div>

enter image description here