Cómo centrar un div

centrado de div

Centrado horizontalmente

Centrar horizontalmente:

  • Establezca un ancho para el div y luego agregue un margen: 0 atributo automático
div{
    
    
            width: 300px;
            margin: 0 auto;
        }
  • Establezca div en inline-block, establezca text-align: center en el elemento principal y deje el ancho del elemento principal sin establecer
<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>
  • Justificar contenido: centrar con diseño flexible;

Centrar horizontal y verticalmente

  • El div absolutamente posicionado está centrado
.container{
    
    
            position: absolute;
            width: 300px;
            height: 300px;
            margin: auto;
            top: 0%;
            left: 0%;
            bottom: 0%;
            right: 0%;
            background-color: rgb(146, 73, 73);
        }
  • arriba: 50%, izquierda: 50%, margen menos la mitad del ancho y alto
.container{
    
    
            position: absolute;
            width: 300px;
            height: 300px;
            margin: -150px 0 0 -150px;
            top: 50%;
            left: 50%;;
            background-color: rgb(146, 73, 73);
        }
  • El ancho y alto del contenedor desconocido, usando transformatributos.
.container{
    
    
            position: absolute;
            width: 300px;
            height: 300px;
            /* translate:移动; */
            left: 50%;
            top: 50%;
            transform: translate(-50%,-50%);
            background-color: rgb(146, 73, 73);
        }
  • Use un diseño flexible para
    prestar atención al elemento principal que debe establecer el ancho y la altura
.container{
    
    
			width:100%;
			height:600px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .bin{
    
    
            width: 300px;
            height: 300px;
            background-color: rgb(228, 127, 127);
        }
  • Utilice los atributos text-align: center y vertical-align: middle
.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;
}

Supongo que te gusta

Origin blog.csdn.net/rraxx/article/details/114698337
Recomendado
Clasificación