Home  >  Article  >  Web Front-end  >  css code for div centering

css code for div centering

下次还敢
下次还敢Original
2024-04-25 14:24:17501browse

Use text-align: center to center a div horizontally in HTML. The steps for vertical centering are as follows: Set the height of the div and the height of the vertical line. Use margin: 0 auto to vertically center content. Centering can also be achieved using flexbox or grid layout.

css code for div centering

CSS code for centered div

centered div

In In HTML, div is a block-level element that is aligned horizontally to the left on the page by default. Center alignment can be achieved using CSS properties.

Horizontal centering

Use the text-align attribute to center the content of the div horizontally.

<code class="css">div {
  text-align: center;
}</code>

Vertical centering

The content of vertically centered divs is more complicated and you need to use the following steps:

  1. Set the height of the div and a vertical Wire.
  2. Use the margin property to center content vertically.
<code class="css">div {
  height: 200px;  /* 设置div的高度 */
  line-height: 200px;  /* 设置垂直线的高度 */
  margin: 0 auto;  /* 将内容垂直居中 */
}</code>

Use flexbox to center

You can also use flexbox layout to center the div.

<code class="css">div {
  display: flex;
  justify-content: center;
  align-items: center;
}</code>

Use grid layout to center

Grid layout can also be used to center divs.

<code class="css">div {
  display: grid;
  place-items: center;
}</code>

The above is the detailed content of css code for div centering. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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