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>
</div>

以上最常用的五种方式,除此之外还有很多方式,根据每个人的习惯不同个人用法不同,如有疑问请谅解。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM