Home  >  Article  >  Web Front-end  >  Detailed examples of two common ways to achieve horizontal and vertical centering of elements in css

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

巴扎黑
巴扎黑Original
2017-05-14 13:37:451699browse

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>

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>

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!

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