Home >Web Front-end >HTML Tutorial >How to center a div in html
There are two ways to center a div in HTML: Use the text-align attribute (text-align: center): suitable for simpler layouts. Use flexible layout (Flexbox): Provide more flexible layout control. The steps include: enabling Flexbox (display: flex) in the parent element. Set the div as a Flex item (flex: 1). Use the align-items and justify-content properties for vertical and horizontal centering.
How to center a div
In HTML, you can use CSS properties to center a div. There are two methods:
Method 1: Use the text-align attribute
This method is suitable for simpler layouts, use the text-align
attribute :
<code class="css">div { text-align: center; }</code>
Method 2: Use flexible layout (Flexbox)
Flexbox is a CSS layout module that provides more flexible layout control. To center a div using Flexbox, use the following steps:
display: flex## for the parent element containing the div #.
<code class="css">.container { display: flex; }</code>
attribute to the div so that it becomes the Flex item of the parent element.
<code class="css">div { flex: 1; }</code>
attribute to vertically center the div.
<code class="css">.container { align-items: center; }</code>
attribute to center the div horizontally.
<code class="css">.container { justify-content: center; }</code>
Example:
<code class="html"><div class="container"> <div>这是居中的内容</div> </div></code>
<code class="css">.container { display: flex; align-items: center; justify-content: center; } div { flex: 1; }</code>
The above is the detailed content of How to center a div in html. For more information, please follow other related articles on the PHP Chinese website!