Allen Ma
Allen Ma

Reputation: 93

How to stop HTML table from resizing?

I'm trying to create a tic-tac-toe game.

A user may click a grid to place a cross. I'm having difficulty figuring out how to place an cross (X) without the table automatically resizing:

As seen in the codepen demo, whenever one clicks a "td" element, the table expands to fill the "X".

I've tried table-layout: fixed and white-space: nowrap to no avail. Can anyone enlighten me on this, or provide a working variant?

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

HTML

<table>
<tr>
    <td style="white-space: nowrap;"></td>
    <td></td>
    <td></td>
</tr>

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

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

CSS

table {
    width: 20%;
    table-layout: fixed;
    border-collapse: collapse;
  }
  td {
    width: 33.333%;
    border: 6px solid black;
  }
  td::after {
    content: '';
    display: block;
    margin-top: 100%;
  }

JS (jquery)

$("td").on("click", function() {
  $(this).text("X");
});

Upvotes: 1

Views: 788

Answers (3)

Hiren Jungi
Hiren Jungi

Reputation: 854

I have updated your code.

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

HTML

<table>
    <tr>
        <td style="white-space: nowrap;"></td>
        <td></td>
        <td></td>
    </tr>

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

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

CSS

table {
    width: 20%;
    table-layout: fixed;
    border-collapse: collapse;
  }
  td {
    width: 33.333%;
    border: 6px solid black;
  }
  td::after {
    content: '';
    display: block;
    margin-top: 100%;
  }
  
.nopos{
  position:absolute;
}

JS

$("td").on("click", function() {
  $(this)
    .html("<div class='nopos'>XXX</div>");
});

Upvotes: 1

GarySweet
GarySweet

Reputation: 1

I believe the answer is in the CSS td::after. When you place the X in the box it creates a new line that increases the box size when entered. To get around this you can just add "float: left" to the td::after CSS rule.

Upvotes: 0

Ashish sah
Ashish sah

Reputation: 755

This can be a better and simple way:

$("td").on("click", function() {
  $(this).text("X");
});
table {
    table-layout: fixed;
    border-collapse: collapse;
 
  }
tr{
  overflow:hidden;
}
  td {
    width: 100px;
    height:100px;
    text-align:center;
    max-width: 33.333%;
    border: 6px solid black;
  }

  
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  
</head>
<body>
  <table>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>

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

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

</body>
</html>

Upvotes: 0

Related Questions