The purpose
I will summarize various methods for centering in HTML that seem simple but are surprisingly tricky to implement.
Preparation
First, confirm what type of tag you want to center.
It will likely be one of the two types below.
The implementation method differs depending on which type of tag you are centering.
contents
Text, images, etc.
Block
Area containing multiple content items
Example: Declared with div
or similar elements
Although tags are given as examples, their behavior can be changed with display
styles.
Therefore, a div
isn’t necessarily always a block, for example.
Implementation
Contents
Horizontal
Specify the text-align: center;
style for the parent tag.
Please note that this style is not applied to elements like span
or img
themselves, as shown in the example below.
Additionally, since this style centers content within its parent block, the parent block (a div
in the example below) needs to either be centered on the screen or have a width of 100%.
<div style ="text-align:center;width:100%">
<span>aaaaa</span>
<img src="img.jpg">
</div>
Example:I have removed the img
(image).
Vertical
Specify the align-content: center;
style for the parenttag.
Please note that this style is not applied to elements like span
or img
themselves, as shown in the example below.
Additionally, since this style centers content within its parent block, the parent block (a div
in the example below) needs to have its height specified.
<div style ="align-content:center;height:500px">
<span>aaaaa</span>
</div>
Example:I have removed the img
(image).
Block
Horizontal
Specify the margin: 0 auto;
style for the tag you want to center.
(The background of the div is set to yellow for clarity.)
<div style ="margin: 0 auto; width:100px; background-color:yellow">
<span>aaaaa</span>
<img src="img.jpg">
</div>
Example:I have removed the img
(image).
Vertical
It’s a bit complicated, but I’ve done it as follows.
(For clarity, I’ve set the background of the div
to yellow and the background of the parent div
to red.)
<div style="height:300px;background-color:red;position: relative;">
<div style="background-color:yellow;position: absolute;height:50%;top: 0;bottom: 0;margin: auto;">
<span>aaaaa</span>
</div>
</div>
Example:I have removed the img
(image).
Result
I was able to center content in HTML.
Appendix
I will introduce code that allows for left-aligned, center-aligned, and right-aligned content, suitable for a document header.
<div style="display:inline-block; width:30%;text-align:left">left</div><div style="display:inline-block; width:40%;text-align:center">center</div>
<div style="display:inline-block; width:30%;text-align:right">right</div>
Example:(The background colors of the left and right elements have been changed.)
comment