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