Home  >  Article  >  Web Front-end  >  An introduction to how to use CSS to center divs horizontally and vertically

An introduction to how to use CSS to center divs horizontally and vertically

高洛峰
高洛峰Original
2017-03-22 15:01:171344browse

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;

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;

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%);

3. CSS3 variable width, horizontal and vertical centering

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

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

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

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