How to center Div with CSS
In web design, it is very important to make the page present a good-looking effect. Centering a Div is a common requirement in designing web pages. Today we will introduce how to use CSS to center a Div.
Method 1: Use the position and transform attributes
The position attribute is used to specify the positioning method of the element, and the transform attribute is used for element conversion.
First, set a fixed width and height in CSS for the Div that needs to be centered, then set its position attribute to absolute, and set both the left and top attributes to 50%; then, use the transform attribute Translate the Div to the upper left by half its own width and height:
.center-div { position: absolute; width: 300px; height: 150px; left: 50%; top: 50%; transform: translate(-50%, -50%); }
This will center the Div horizontally and vertically in the parent container.
Method 2: Use Flex Layout
Flex layout is a new layout method introduced in CSS3, which can be used to center elements both horizontally and vertically.
First, set the display attribute of the parent container to flex, then set the justify-content attribute to center, which will center the content horizontally; then set the align-items attribute to center, which will Center the content vertically.
.parent { display: flex; justify-content: center; align-items: center; } .parent .center-div { width: 300px; height: 150px; }
Method 3: Use text-align and vertical-align attributes
Applicable to situations where there is only one line of text inside.
To center a Div, you can use the text-align attribute in the parent container to center the internal text horizontally, and the vertical-align attribute to center the text vertically.
.parent { text-align: center; line-height: 150px; } .parent .center-div { display: inline-block; vertical-align: middle; width: 300px; height: 150px; }
Summary:
The above three methods to achieve element centering are to first set some attributes on the parent container, and then impose some restrictions on the child elements. Which method to use needs to be chosen according to the specific situation. CSS is very flexible and we need to master its various uses in order to achieve free play in web design.
The above is the detailed content of How to center div with css. For more information, please follow other related articles on the PHP Chinese website!