为什么div的宽度不按定义工作?

时间:2017-09-11 11:05:15

标签: html

我的目标是在父div中嵌套5个div。 每个div都同样宽,并排。

这是我的HTML:



<div style="margin-left: auto; margin-right: auto; width: 80%;">
    
    <div style="display: table-row;">
    <div style="display: table-cell; text-align: center; width: 20%;">Left</div>
    <div style="display: table-cell; text-align: center; width: 20%;">Left</div>
    <div style="display: table-cell; text-align: center; width: 20%;">Left</div>
    <div style="display: table-cell; text-align: center; width: 20%;">Left</div>
    <div style="display: table-cell; text-align: center; width: 20%;">Left</div>
    </div>

    </div>
&#13;
&#13;
&#13;

并排功能正在运行,但不是宽度。它只是挤在左边。有什么想法吗?

5 个答案:

答案 0 :(得分:1)

问题是您使用table-row而不在table内。

<div style="margin-left: auto; margin-right: auto; width: 80%;display:table">

  <div style="display: table-row;background-color:green;">
    <div style="display: table-cell; text-align: center; width: 20%;">Left</div>
    <div style="display: table-cell; text-align: center; width: 20%;">Left</div>
    <div style="display: table-cell; text-align: center; width: 20%;">Left</div>
    <div style="display: table-cell; text-align: center; width: 20%;">Left</div>
    <div style="display: table-cell; text-align: center; width: 20%;">Left</div>
  </div>

</div>

答案 1 :(得分:1)

使用flex-boxes可以很好地实现这一点。

<div style="margin-left: auto; margin-right: auto; width: 80%; display: flex">
    <div style="flex: 1; text-align: center;">Left</div>
    <div style="flex: 1; text-align: center;">Left</div>
    <div style="flex: 1; text-align: center;">Left</div>
    <div style="flex: 1; text-align: center;">Left</div>
    <div style="flex: 1; text-align: center;">Left</div>
</div>

答案 2 :(得分:0)

尝试更改

<div style="display: table-row;">

<div style="display: table; width:100%;">

答案 3 :(得分:0)

要实现此目的,您需要将display: table;设置为外部div:

<div style="margin-left: auto; margin-right: auto; width: 80%;display:table">
    <div style="display: table-row;">
        <div style="display: table-cell; text-align: center; width: 20%;">Left</div>
        <div style="display: table-cell; text-align: center; width: 20%;">Left</div>
        <div style="display: table-cell; text-align: center; width: 20%;">Left</div>
        <div style="display: table-cell; text-align: center; width: 20%;">Left</div>
        <div style="display: table-cell; text-align: center; width: 20%;">Left</div>
    </div>
</div>

答案 4 :(得分:0)

使用display: flex并将所有元素加宽到100%。

&#13;
&#13;
.wrapper {
  display: flex;
}

.wrapper > div {
  width: 100%;
}
&#13;
<div class="wrapper">
  <div>Left</div>
  <div>Left</div>
  <div>Left</div>
  <div>Left</div>
  <div>Left</div>
</div>
&#13;
&#13;
&#13;