Reputation: 1867
I have a div:
<div id="tableContainer">
</div>
and I'm dynamically adding a table to this with jQuery:
$(document).ready(function () {
var data = '[{"gameid":"1","gamename":"Halo","gamedescription":"Game about aliens","gamegenre":"FPS"},{"gameid":"2","gamename":"Halo 2","gamedescription":"Game about aliens 2","gamegenre":"FPS"}]';
var json = $.parseJSON(data);
$("#tableContainer").append("<table>");
$("#tableContainer").append("<tr>");
$("#tableContainer").append("<td>Game ID</td>");
$("#tableContainer").append("<td>Game Name</td>");
$("#tableContainer").append("<td>Game Description</td>");
$("#tableContainer").append("<td>Game Genre</td>");
$("#tableContainer").append("</tr>");
$.each(json, function (index, value) {
$("#tableContainer").append("<tr>");
console.log(value.gameid);
$("#tableContainer").append("<td>" + value.gameid + "</td>");
$("#tableContainer").append("<td>" + value.gamename + "</td>");
$("#tableContainer").append("<td>" + value.gamedescription + "</td>");
$("#tableContainer").append("<td>" + value.gamegenre + "</td>");
$("#tableContainer").append("</tr>");
});
$("#tableContainer").append("</table>");
});
and I want to horizontally center this entire table. I'm trying to use
#tableContainer {
text-align: center;
width: 100%;
}
#table {
margin: 0 auto;
}
but having no success. Any ideas? Here is a fiddle:
http://jsfiddle.net/bn52jk8k/11/
Thanks
Upvotes: 1
Views: 40
Reputation: 1192
Modify code like this
$(document).ready(function () {
var data = '[{"gameid":"1","gamename":"Halo","gamedescription":"Game about aliens","gamegenre":"FPS"},{"gameid":"2","gamename":"Halo 2","gamedescription":"Game about aliens 2","gamegenre":"FPS"}]';
var json = $.parseJSON(data);
var table="<table>"
+ "<tr>"
+ "<td>Game ID</td>"
+ "<td>Game Name</td>"
+ "<td>Game Description</td>"
+ "<td>Game Genre</td>"
+ "</tr>";
$.each(json, function (index, value) {
table+="<tr>"
+ "<td>" + value.gameid + "</td>"
+ "<td>" + value.gamename + "</td>"
+ "<td>" + value.gamedescription + "</td>"
+ "<td>" + value.gamegenre + "</td>"
+ "</tr>";
});
table+="</table>";
$("#tableContainer").append(table);
});
and in CSS,
#tableContainer table {
margin: 0 auto;
}
Here is the fiddle; Jsfiddle Center align
Upvotes: 3