How to center the DIV box in the center of the screen
Method 1: Use CSS property
-
text-align : center; Center the container element.
-
margin: auto; Sets automatic margins on a container element, which will center the element within the container.
HTML code:
<code class="html"><div style="text-align: center; margin: auto;">
您的内容在此
</div></code>
Copy after login
Method 2: Using flexbox
-
display: flex; Convert container elements to flexbox.
-
justify-content: center; Center the element on the main axis (horizontally).
-
align-items: center; Center the element on the cross axis (vertical direction).
HTML code:
<code class="html"><div style="display: flex; justify-content: center; align-items: center;">
您的内容在此
</div></code>
Copy after login
Method 3: Use absolute positioning
-
position : absolute; Removes the element from the normal document flow.
-
left: 50%; Moves the element from the left by half its width.
-
transform: translate(-50%, -50%); Moves the element half its width and height to the left and up from the center point.
HTML Code:
<code class="html"><div style="position: absolute; left: 50%; transform: translate(-50%, -50%);">
您的内容在此
</div></code>
Copy after login
Additional Notes:
- In some cases, you may Margins or other style values need to be adjusted to ensure proper centering.
- Make sure the container element is large enough to hold your content.
- These methods work in all modern browsers.
The above is the detailed content of How to center the div box in the center of the screen in html. For more information, please follow other related articles on the PHP Chinese website!