Home > Web Front-end > HTML Tutorial > How to center a div in html

How to center a div in html

下次还敢
Release: 2024-04-05 09:00:23
Original
948 people have browsed it

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

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>
Copy after login

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:

  1. Enable Flexbox in the parent element: Set display: flex## for the parent element containing the div #.
  2. <code class="css">.container {
      display: flex;
    }</code>
    Copy after login
  1. Set the div as a Flex item: Set the flex attribute to the div so that it becomes the Flex item of the parent element.
  2. <code class="css">div {
      flex: 1;
    }</code>
    Copy after login
  1. Vertical centering: Use the align-items attribute to vertically center the div.
  2. <code class="css">.container {
      align-items: center;
    }</code>
    Copy after login
  1. Horizontal centering: Use the justify-content attribute to center the div horizontally.
  2. <code class="css">.container {
      justify-content: center;
    }</code>
    Copy after login

Example:

<code class="html"><div class="container">
  <div>这是居中的内容</div>
</div></code>
Copy after login
<code class="css">.container {
  display: flex;
  align-items: center;
  justify-content: center;
}

div {
  flex: 1;
}</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template