Things I want to do
This article summarizes methods for centering text in HTML, a technique that seems simple but is surprisingly difficult.
Prepare
First, identify which tag you want to center.
It’s probably one of the following two options.
The implementation method differs depending on which tag you want to center.
content
Text and images, etc.
block
Area containing multiple content
Example: Declared in a div, etc.
The example uses tags, but this can be changed using the display style.
Therefore, a `div` is not necessarily a block element.
implementation
content
Lateral direction
ParentsThe tag is given the style `text-align:center`.
Please note that you should not set this in a span or img as shown in the example below.
Also, since this style displays the content in the center of its parent block, the parent block (a div in the example below) must be displayed in the center of the screen or with a width of 100%.
<div style ="text-align:center;width:100%">
<span>aaaaa</span>
<img src="img.jpg">
</div>Example:I’ve deleted the image.
Vertical
ParentsThe tag is given the style `align-content: center`.
Please note that you should not set this in a span or img as shown in the example below.
Also, since this style displays the element in the center of its parent block, you need to specify the height of the parent block (a div in the example below).
<div style ="align-content:center;height:500px">
<span>aaaaa</span>
</div>Example:I’ve deleted the image.
block
Lateral direction
Specify the style `margin: 0 auto` for the tags you want to center.
(The background of the div is yellow for clarity.)
<div style ="margin: 0 auto; width:100px; background-color:yellow">
<span>aaaaa</span>
<img src="img.jpg">
</div>Example:I’ve removed the image.
Vertical
It’s a bit of a hassle, but I did it like this.
(For clarity, the background of the div is yellow and the background of the parent div is 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’ve deleted the image.
Result
I was able to center the text using HTML.
bonus
Here is some code for left-aligned, center-aligned, and right-aligned text for document headers.
<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 on the left and right have been changed.)


コメント