元素水平垂直居中的三种方式

文章目录

  • 方法一:
  • 方法二:
  • 方法三:
  • 最后


方法一:

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .father{
            width: 400px;
            height: 400px;
            border: 1px solid;
            position: relative;
        }
        .son{
            position: absolute;
            width: 200px;
            height: 200px;
            background-color: red;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            margin: auto;
        }
    style>
head>
<body>
    <div class="father">
        <div class="son">div>
    div>
body>
html>

方法二:

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        
        .father{
            width: 400px;
            height: 400px;
            border: 1px solid;
            position: relative;
        }
        .son{
            position: absolute;
            width: 200px;
            height: 200px;
            background-color: blue;
            top: 50%;
            left: 50%;
            transform: translate(-50%,-50%);
        }
    style>
head>
<body>
    <div class="father">
        <div class="son">div>
    div>
body>
html>

方法三:

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .father{
            display: flex;
            justify-content: center; /*justify-content属性定义了项目在主轴上的对齐方式*/
            align-items: center; /* align-items属性定义项目在交叉轴上如何对齐 */
            width: 400px;
            height: 400px;
            border: 1px solid;
        }
        .son{
            width: 200px;
            height: 200px;
            background-color: green;
        }
    style>
head>
<body>
    <div class="father">
        <div class="son">div>
    div>
body>
html>

最后

元素水平垂直居中的方式常见的我知道的就是这三种了,希望对你有帮助

你可能感兴趣的:(前端,css,javascript)