How to achieve vertical centering of page elements through CSS Flex elastic layout
In web design, we often encounter situations where page elements need to be vertically centered. CSS Flex layout is an elegant, concise and flexible layout method that can easily achieve vertical centering of page elements. This article will introduce in detail how to use CSS Flex layout to achieve vertical centering of page elements and provide specific code examples.
1. Basic principles
Using CSS Flex layout to achieve vertical centering of page elements requires the following basic principles:
2. Specific implementation
The following is a simple example to demonstrate how to use CSS Flex layout to achieve vertical centering of page elements:
<div class="container"> <div class="content"> <p>这是要垂直居中的内容</p> </div> </div>
.container { display: flex; /* 设置为Flex布局 */ justify-content: center; /* 水平居中 */ align-items: center; /* 垂直居中 */ height: 100vh; /* 设置容器高度为100视口高度,使容器占据整个屏幕 */ } .content { background-color: #f0f0f0; padding: 20px; }
In the above code, we first set the parent container to Flex layout, and use the justify-content attribute to set its child elements in Align it horizontally in the center, and use the align-items attribute to center align its child elements in the vertical direction. At the same time, in order to make the container occupy the entire screen, we use the height: 100vh attribute.
3. Example effect
Through the above code, we successfully achieved vertical centering of page elements. After you run the sample code, you'll see "This is the content to be vertically centered" displayed vertically centered on the page, and the container will take up the entire screen.
4. Summary
Vertical centering of page elements can be easily achieved through CSS Flex elastic layout. You only need to set the parent container to Flex layout, and use the justify-content and align-items attributes to control the alignment of elements on the main axis and cross axis respectively, to achieve a simple and effective vertically centered layout. I hope this article can help you better apply CSS Flex layout and improve your web design capabilities.
The above is the detailed content of How to achieve vertical centering of page elements through CSS Flex layout. For more information, please follow other related articles on the PHP Chinese website!