How to Align Horizontally in JavaScript TD
In both JavaScript and HTML, the "<td>" tag defines a table cell element. Before creating a table element, create a table with the "<table>" tag and a table row with the "<tr>" tag. Align content horizontally by attaching the "align='center'" attribute to the <td> tag (deprecated in HTML version 5) or by using CSS to set the left and right margins to auto and setting the "text-align:center" attribute for the cell.
Instructions
-
-
1
Create a new HTML document using Notepad or an HTML editor. Enter the HTML headers into the document:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Center Table Cell</title>
-
2
Create a CSS style definition that will center the contents of a table cell by creating a class with the left and right margins equal to "auto" and "text-align" set to "center:"
<style>
.ccell { margin-left:auto; margin-right:auto; text-align:center; }
</style>
-
-
3
Create a JavaScript function that will get the "id" of a table cell and add the CSS class to center the cell contents:
<script>
function centerIt() {
var c = document.getElementById("theCell");
c.className += "ccell";
}
</script>
</head>
-
4
Create an HTML table using the <table> tag, add a new row using the <tr> tag and add a new cell using the <td> tag. Assign the same "id" used in the JavaScript function to the cell. Close all three tags:
<body>
<table width="800" border="1">
<tr>
<td id="theCell">Here is some text to be centered</td>
</tr>
</table>
-
5
Create an HTML form with a button that will call the JavaScript function to horizontally center the contents of the <td> when clicked:
<form name="myForm">
<input type="button" value="Center" onClick="centerIt();">
</form>
</body>
</html>
-
6
Save the HTML file. Open it with a browser and view the initial text left-justified in the table cell. Click the button and watch the text become horizontally centered.
-
1