[CSS] Positioning elements are displayed in the center

高洛峰
Release: 2017-02-22 13:47:20
Original
1397 people have browsed it

1. Use margin


p {
    width: 100px;
    height: 100px;
    background-color: skyblue;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;}
Copy after login


## Analysis:

  • top: 50%; left: 50%; Let the top left of the element be vertically and horizontally centered in the parent element

  • margin-top: -50px; margin-left: -50px; Let The element is offset half its distance upward and to the right

2. Use translate


p {
    width: 100px;
    height: 100px;
    background-color: skyblue;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);}
Copy after login


Analysis:

  • top: 50%; left: 50%; Let the top left of the element be vertically and horizontally centered in the parent element

  • transform: translate(-50%, -50%); Move the element up and to the right by half its distance

3. All four directions are 0, use margin Positioning


p {
    width: 100px;
    height: 100px;
    background-color: skyblue;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right : 0;
    margin: auto;}
Copy after login


Analysis:

  • All four directions When it is 0, they cancel each other out, and the box will be displayed at the initial position

  • margin: auto; center the box vertically and horizontally

More【CSS 】For related articles about centered display of positioning elements, please pay attention to the PHP Chinese website!

Related labels:
css
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!