Search code examples
csswidth

CSS Width not Applying


Why are my ps of different widths for the code below?

I've tried wrapping them in a table and adding width:100% as per css width property not applying properly but that didn't help.

body {
  background-color: aliceblue;
}

p {
  border-radius: 5px;
  background-color: cadetblue;
  font-size: 64px;
  width: 90px;
  text-align: -webkit-center;
  color: white;
  height: 90px;
  display: table-cell;
  vertical-align: middle;
  font-family: helvetica;
}
<p>0</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>10</p>
<p>11</p>
<p>12</p>
<p>13</p>
<p>14</p>
<p>15</p>
<p>&nbsp;</p>


Solution

  • From the specification:

    table, inline-table, table-row-group, table-column, table-column-group, table-header-group, table-footer-group, table-row, table-cell, and table-caption These values cause an element to behave like a table element (subject to restrictions described in the chapter on tables).

    Basically you are facing some default behavior of tables.

    Here is an example to illustrate a similar situation:

    td {
     width:100px; /* This is restricted by the width of table*/
     border:1px solid;
    }
    <table>
      <tr>
        <td>2</td>
        <td>1</td>
        <td>1</td>
        <td>2</td>
        <td>2</td>
        <td>1</td>
        <td>1</td>
        <td>2</td>
        <td>2</td>
        <td>1</td>
        <td>1</td>
        <td>2</td>
        <td>2</td>
        <td>1</td>
        <td>1</td>
        <td>2</td>
        <td>2</td>
        <td>1</td>
        <td>1</td>
        <td>2</td>
      </tr>
    </table>
    <table>
      <tr>
        <td>2</td>
        <td>1</td>
        <td>1</td>
        <td>2</td>
        <td>2</td>
        <td>1</td>
        <td>1</td>
      </tr>
    </table>

    Instead of tables simply rely on something else

    body {
      background-color: aliceblue;
    }
    .container {
      font-size:0; /* remove white space */
      white-space:nowrap; /* Keep one line */
    }
    p {
      border-radius: 5px;
      background-color: cadetblue;
      font-size: 64px;
      width: 90px;
      text-align:center;
      color: white;
      height: 90px;
      line-height:90px; /*vertical align */
      display:inline-block;
      font-family: helvetica;
    }
    <div class="container">
    <p>0</p>
    <p>1</p>
    <p>2</p>
    <p>3</p>
    <p>4</p>
    <p>5</p>
    <p>6</p>
    <p>7</p>
    <p>8</p>
    <p>9</p>
    <p>10</p>
    <p>11</p>
    <p>12</p>
    <p>13</p>
    <p>14</p>
    <p>15</p>
    <p>&nbsp;</p>
    </div>