This guide explains the procedure of setting the “vertical alignment” to “middle” in JavaScript.
How to Set “vertical alignment” to “middle” in JavaScript?
The Style “verticalAlign” property works on the key “value” that sets the vertical alignment of the particular HTML element to the middle or wherever the user wants. It only applies to the “inline block”, “table-cell”, and “inline element” and cannot be implemented on the block-level components.
Syntax
In the above syntax:
- element: It represents the targeted HTML element.
- value: It specifies the key value that can be “left”, “right”, “bottom”, or “middle”.
Example: Applying the “vertical alignment” Property to Set the HTML Content i.e., Table Data in the “middle”
This example shows the practical implementation of the “verticalAlign” property to set the content of the table in the “middle”.
HTML Code
First, have a look at the following code:
In the above code snippet:
- The “<h3>” states the level 3 subheading.
- The “<table>” tag creates a table comprising the row via the “<tr>” tag and inserts a data cell in it using the “<td>” tag having id “demo” and the “vertical-align” attribute set to “top”.
- The “<br>” tag adds a line break.
- The “<button>” tag includes a button with an attached “onclick” event that allows the execution of the “myFunc()” function on the button click.
JavaScript Code
Consider the following code snippet:
In the above code:
- Define a function named “myFunc()”.
- In its definition, the “getElementById()” method is utilized that fetches the data cell using its id “demo” and sets its vertical alignment into “middle” via the “verticalAlign” property.
Output (Before Button Click)
As seen before the button click, the fetched HTML element is on its existing vertical alignment position i.e., “top”.
Output (After Button Click)
This output implies that the vertical alignment of the specified HTML is set to “middle” upon the button click.
Conclusion
In JavaScript, the Style “verticalAlign” property sets the vertical alignment of the associated HTML element to “middle”. Apart from the middle, it also assists the users to align the vertical alignment at the “bottom”, “top”, “initial text-top”, and other supported positions. This guide demonstrated the complete procedure to set the “vertical alignment” to “middle” in JavaScript.