HTML中5种常见的居中⽅法
第⼀种:将元素通过display:inline-block转化为⾏内块元素居中,例如:
<style>
.box{width:500px;height:500px;box-shadow:0 0 5px #000;text-align:center;font-size:0;}
.box .zi{width:120px;height:100px;background:#0f0;display:inline-block;vertical-align:middle;}
.box:after{content:"";display:inline-block;height:100%;vertical-align:middle;}
</style>
</head>
<body>
<div class="box">
<div class="zi"></div>
</div>
第⼆种:⽤定位的⽅式将之移动到位置,例如:
<style>
.box{width:500px;height:500px;box-shadow:0 0 5px #000;position:relative;}
.box .zi{width:120px;height:100px;background:#0f0;
position:absolute;left:0;right:0;top:0;bottom:0;margin:auto;}
</style>
</head>
<body>
<div class="box">
<div class="zi"></div>
</div>
第三种:类似第⼆中只不过通过百分⽐调整位置,例如
<style>
.box{width:500px;height:500px;box-shadow:0 0 5px #000;position:relative;}
.box .zi{width:120px;height:100px;background:#0f0;position:absolute;left:50%;top:50%;margin:-50px 0 0 -60px;} </style>
</head>
<body>
<div class="box">
<div class="zi"></div>
</div>
第四种:类似第三种,但是在调整回到中⼼位置时使⽤transform:translate(,)进⾏调整,例如
<style>
.box{width:500px;height:500px;box-shadow:0 0 5px #000;position:relative;}
.box .zi{width:120px;height:100px;background:#0f0;
position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);}
</style>
</head>
<body>
<div class="box">
<div class="zi"></div>
</div>
第五种:使⽤弹性盒(display:flex),例如
<style>
.box{width:500px;height:500px;box-shadow:0 0 5px #000;display:flex;justify-content:center;align-items:center;} .box .zi{width:120px;height:100px;background:#0f0;}
</style>
</head>
<body>
<div class="box">
<div class="zi"></div>
html全部居中代码</div>
以上最常⽤的五种⽅式,除此之外还有很多⽅式,根据每个⼈的习惯不同个⼈⽤法不同,如有疑问请谅解。