How to center a div

centering of div

Horizontally centered

Center horizontally:

  • Set a width to the div, and then add a margin:0 auto attribute
div{
    
    
            width: 300px;
            margin: 0 auto;
        }
  • Set div to inline-block, set text-align:center to the parent element, and leave the width of the parent element unset
<style>
        .container {
    
    
            background: rgba(0, 0, 0, 0.5);
            text-align: center;
            font-size: 0;
            }

            .box {
    
    
            display: inline-block;
            width: 500px;
            height: 400px;
            background-color: pink;
            }
    </style>
</head>
<body>
    <div class="container">
        <div class="box"></div>
    </div>
  • Justify-content: center using flex layout;

Center horizontally and vertically

  • Absolutely positioned div is centered
.container{
    
    
            position: absolute;
            width: 300px;
            height: 300px;
            margin: auto;
            top: 0%;
            left: 0%;
            bottom: 0%;
            right: 0%;
            background-color: rgb(146, 73, 73);
        }
  • top: 50%, left: 50%, margin minus half of width and height
.container{
    
    
            position: absolute;
            width: 300px;
            height: 300px;
            margin: -150px 0 0 -150px;
            top: 50%;
            left: 50%;;
            background-color: rgb(146, 73, 73);
        }
  • The width and height of the unknown container, using transformattributes
.container{
    
    
            position: absolute;
            width: 300px;
            height: 300px;
            /* translate:移动; */
            left: 50%;
            top: 50%;
            transform: translate(-50%,-50%);
            background-color: rgb(146, 73, 73);
        }
  • Use flex layout to
    pay attention to the parent element must set the width and height
.container{
    
    
			width:100%;
			height:600px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .bin{
    
    
            width: 300px;
            height: 300px;
            background-color: rgb(228, 127, 127);
        }
  • Use text-align: center and vertical-align: middle attributes
.container {
    
    
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  text-align: center;
  font-size: 0;
  white-space: nowrap;
  overflow: auto;
}

.container::after {
    
    
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

.box {
    
    
  display: inline-block;
  width: 500px;
  height: 400px;
  background-color: pink;
  white-space: normal;
  vertical-align: middle;
}

Guess you like

Origin blog.csdn.net/rraxx/article/details/114698337