Detailed examples of two common ways to achieve horizontal and vertical centering of elements in css

巴扎黑
Release: 2017-05-14 13:37:45
Original
1744 people have browsed it

This article mainly introduces you to two ways to achieve horizontal and vertical centering of elements in CSS. The article provides a complete sample code for your reference and study. It has certain reference value for your study or work. If necessary, Friends, let’s take a look together.

1. The flex layout of the parent element realizes the horizontal and vertical centering of the element

The sample code is as follows:


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    .parent{
      display:flex;
      display:-webkit-flex;
      justify-content: center;
      align-items: center;
      width:100%;
      height: 200px;
      background-color: #c43;
    }

    .child{
      width:300px;
      height:100px;
      background-color: #c4235b;
    }
  </style>
</head>
<body>
  <p class="parent">
    <p class="child"></p>
  </p>
</body>
</html>
Copy after login

The rendering is as follows:

## 2. Absolute positioning & negative The margin value implements horizontal and vertical centering of the element

Note:The element itself needs to determine the width and height

Example The code is as follows:


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    p{
      width:300px;
      height:100px;
      background-color: #873cac;
      position:absolute;
      top:50%;
      left:50%;
      margin-left: -150px;
      margin-top:-50px;
    }  
  </style>
</head>
<body>
  <p></p>
</body>
</html>
Copy after login

The rendering is as follows:

The above is the detailed content of Detailed examples of two common ways to achieve horizontal and vertical centering of elements in css. 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