D Lamar D Lamar - 6 months ago 10
CSS Question

css table centering in IE11 but not in Chrome/Firefox

Have a header, two buttons and two tables in my Html.
When webpage is first launched table associated with 'first' button is displayed. The table associated with second button is not displayed.

When 'second' button is clicked, table associated with second button is displayed and the first table is not displayed.

The code works fine in IE11 and the table is centered as desired in IE11; but the table does not get centered in chrome/firefox.

HTML:



<!DOCTYPE html>
<html>
<head>
<title>All Stock Data</title>
<link rel="stylesheet" href="stock.css" type="text/css">
<script type="text/javascript" src="stock.js" ></script>
</head>

<body>

<h1>Stock Data</h1>

<div class="mytoggle">
<button onclick="toggleDisplay('first')" id="button_first">First</button>
<button onclick="toggleDisplay('second')" id="button_second">Second</button>
</div>

<table id="first">

<tr>
<th>Name</th>
<th>Color</th>
<th>Shape</th>
</tr>



<tr>
<td>O1</td>
<td>Blue</td>
<td>Square</td>
</tr>

<tr>
<td>L1</td>
<td>Brown</td>
<td>Circle</td>
</tr>

</table>

<table id="second">

<tr>
<th>Name</th>
<th>Color</th>
<th>Shape</th>
</tr>



<tr>
<td>H2</td>
<td>White</td>
<td>Round</td>
</tr>

<tr>
<td>M2</td>
<td>Gray</td>
<td>Square</td>
</tr>

</table>

</body>
</html>


CSS:



table {
border-collapse: collapse;
margin: auto;
}

table#first {
display: block;
}
table#second {
display: none;
}


Javascript:



function toggleDisplay(myTableId)
{
if(myTableId == "first"){
document.getElementById('first').style.display = "block";
document.getElementById('second').style.display = "none";

/*background*/
document.getElementById('button_first').style.background = "blue";
document.getElementById('button_second').style.background = "gray";
}


if(myTableId == "second"){
document.getElementById('first').style.display = "none";
document.getElementById('second').style.display = "block";

/*background*/
document.getElementById('button_first').style.background = "gray";
document.getElementById('button_second').style.background = "blue";
}

}

Answer

CSS (replace the one that's there):

table#first {
  display: table;
}

Script:

function toggleDisplay(myTableId)
{
  if(myTableId == "first"){
     document.getElementById('first').style.display = "table";
     document.getElementById('second').style.display = "none";
  }
  if(myTableId == "second"){
     document.getElementById('first').style.display = "none";
     document.getElementById('second').style.display = "table";
  }
}

In short, everywhere you set a <table> to display as block you are getting hosed. A <table> is not block. So use display:table. More info going back to CSS 2.

Comments