[css] How to center a “position: absolute” element

How to center with position: absolute css

When using position to position an element, you may often want to center the element. Have you ever wondered what to do in this case?
In this article, I will show you how to set up a css that allows you to center the top and bottom, left and right, top and bottom, left and right, even if the width of the element is not fixed in position.

How to center an element using position and translate

Specific examples and explanations

Now, I would like to explain the actual installation method with specific examples.
The example is a case where text is placed on top of an image, and the position of the text should be centered at the top, bottom, left, and right.
The completed image is shown in the figure below. (It may be difficult to understand, but please assume that the light blue part is the image [img].)

image drawing

Now, I would like to explain it after showing the source in detail.
First, please check your html and css.

html

css

This part is not really related to the main topic, so I will skip the css explanation, but please assume that the size of the img placed in html is the same as the size of .box.
p “Sample Text” will be the element you want to center.
As for the css, the first thing to do is to place p at 50% of the top and bottom position. This means that the upper right part of p will be placed right in the middle of the .box. Then, you can use transform to place it at the desired position. If you set -50% for up and down in transform, it will move by -50% of the size of . Then the p will be placed right in the center.

Summary

In the examples and explanations, we introduced how to place elements at the top, bottom, left, right, and center, but of course it is also possible to place only the top, bottom, left, and right at the center. The following is a summary of the installation method.

For placement in the center of top, bottom, left and right

To center the top and bottom

To center the left and right