具有自动宽度的三个div的宽度与最宽的div的宽度一样,使每个div与其内容的宽度一样

时间:2019-02-13 00:03:03

标签: html css

我有一个.yellow-element样式的三个div width: auto,位于一个宽度也为auto的表列中。这导致表的宽度和最宽的div 一样大,而则使每个div都变得最宽,即使这不是按内容的必要:

#info-table td {
    padding: 10px;
    border: 1px solid #ddd;

}

.info-table-1  {

    width: 100px;
}

.info-table-2  {
    width: auto;
}

.yellow-element  {
    font-size: 100%;    
    font-weight: bold;
    color: var(--body-font-color);
    background-color: yellow;
    border: 1px solid black;
    border-radius: 25px;
    padding: 5px;
    margin-right: 20px;

    width: auto;
    height: 30px;

    margin-bottom: 15px;
}
<table id="info-table">
  <tr>
    <td class='info-table-1'>Total Something:</td>
    <td class='info-table-2'>
       100500/100500
    </td>
  </tr>

  <tr><td class='info-table-1'>Yellow Elements:</td>
    <td class='info-table-2'>
      <div class='yellow-element' title='title1'>long long long long long long long long long long long long long text</div>

      <div class='yellow-element' title='title2'>average average average text </div>

      <div class='yellow-element' title='title3'>small text</div>

    </td></tr>
</table>

我见过的答案建议将display: inline-block放在类.yellow-element上,但是虽然它确实起作用,但单独固定每个div的宽度,却将所有div放在同一行上,即不是我想要的。

Codepen:https://codepen.io/anon/pen/zeaXbL

2 个答案:

答案 0 :(得分:2)

您可以将.info-table-2放入flex容器。然后,您可以更轻松地控制yellow-element单元的布局。

#info-table td {
  padding: 10px;
  border: 1px solid #ddd;
}

.info-table-1 {
  width: 100px;
}

.info-table-2 {
  /* width: auto; */         /* <-- removed */
  display: flex;             /* <-- added */
  flex-direction: column;    /* <-- added */
  align-items: flex-start;   /* <-- added */
}

.yellow-element {
  font-size: 100%;
  font-weight: bold;
  color: var(--body-font-color);
  background-color: yellow;
  border: 1px solid black;
  border-radius: 25px;
  padding: 5px;
  margin-right: 20px;
  width: auto;
  height: 30px;
  margin-bottom: 15px;
}
<table id="info-table">
  <tr>
    <td class='info-table-1'>Total Something:</td>
    <td class='info-table-2'>
      100500/100500
    </td>
  </tr>

  <tr>
    <td class='info-table-1'>Yellow Elements:</td>
    <td class='info-table-2'>
      <div class='yellow-element' title='title1'>long long long long long long long long long long long long long text</div>

      <div class='yellow-element' title='title2'>average average average text </div>

      <div class='yellow-element' title='title3'>small text</div>

    </td>
  </tr>
</table>

https://jsfiddle.net/r3bwqn4u/1/

答案 1 :(得分:1)

使用以下内容:

.yellow-element {
   clear:both;
   float:left;
}