Two methods to use CSS to center the Div as a whole: Use the text-align attribute to set text-align: center for the parent container so that the child elements are horizontally centered within the parent container. Use the margin property to set margin: auto for a Div to center the Div horizontally.
How to use CSS to center a Div as a whole
Using CSS There are two main methods to center a Div as a whole: Use text-align
attribute and use the margin
attribute.
Use the text-align
attribute
text-align: center
for the parent container. This will center-align the child element horizontally within its parent container. Use the margin
attribute
margin: auto
for the Div. This will set the Div's left and right margins to automatic, centering it horizontally. Example
<code class="css">/* 使用 text-align 属性 */ .parent-container { text-align: center; } .child-div { /* 无需设置任何属性,已由父容器居中 */ } /* 使用 margin 属性 */ .div-with-margin { margin: auto; /* 无需设置任何其他属性 */ }</code>
Note:
margin
attribute , the Div will be centered relative to its parent container. If the parent container does not have an explicit width, the Div will not be centered. text-align
attribute, if a Div contains block-level elements, those elements will be centered relative to the Div, not the parent container. vertical-align
attribute or the transform
attribute. The above is the detailed content of How to center the div as a whole in css. For more information, please follow other related articles on the PHP Chinese website!