Home > Web Front-end > CSS Tutorial > Use CSS to center div horizontally and vertically

Use CSS to center div horizontally and vertically

迷茫
Release: 2017-03-25 09:56:03
Original
1468 people have browsed it

There are many solutions to achieve centering. Here we introduce the solution of pure CSS using absolute with margin.

1. p width and height are fixed

width: 400px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -200px;
Copy after login

margin-top is -(height / 2), margin-left is -(width / 2). Of course, you can not use margin, that is, top is calc(100% - height) / 2, left is calc(100% - width) / 2, but it is recommended not to use calc() if you don't need it.

2. pThe width and height are not fixed

width: 50%;
height: 50%;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
Copy after login

Note that this applies to situations where the width and height need to be specified, such as using percentages or using js Modify dynamically, otherwise it may be treated as 100%.

You can also use translate() without margin, as follows:

width: 50%;
height: 50%;
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
Copy after login

3. CSS3 variable width, horizontal and vertical centering

justify-content: center; /* 子元素水平居中 */
align-items: center;     /* 子元素垂直居中 */
display: -webkit-flex;
Copy after login

in the parent element Add it to achieve horizontal and vertical centering of child elements.

The above is the detailed content of Use CSS to center div horizontally and vertically. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template