1. 程式人生 > >寬度不固定上下水平居中

寬度不固定上下水平居中

想要實現寬度不固定的div上下水平居中這裡介紹三種實現方法

1,flex

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
html,body{
            width: 100%;
height: 100%;
}
        .content{
            width: 100%;
height: 100%;
display: flex;
justify-content
: space-between; } .left,.middle,.right{ width: 200px; height: 100%; } .left{ background: pink; } .middle{ background: lightskyblue; flex: 1; } .right{ background: plum; } </style> </head> <body> <div
class="content"> <div class="left"></div> <div class="middle"></div> <div class="right"></div> </div> </body> </html>

2,table-cell+vertical-align

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>
Title</title> <style> html,body{ width: 100%; height: 100%; } .content{ width: 500px; height: 500px; background: rgba(0,0,0,0.3); display: table-cell; vertical-align: middle; text-align: center; } .center{ width: 200px; height: 200px; background: red; display: inline-block; } </style> </head> <body> <div class="content"> <div class="center"></div> </div> </body> </html>

3,定位+translate

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
html,body{
        width: 100%;
height: 100%;
}
    .centent1{
        width: 500px;
height: 500px;
background: rgba(0,0,0,0.3);
position: relative;
}
    .center{
        width: 200px;
height: 200px;
background: red;
transform: translate(-50%,-50%);
position: absolute;
top: 50%;
left: 50%;
}
</style>
<body>
<p>上下水平居中定位</p>
<div class="centent1">
    <div class="center"></div>
</div>
</body>
</html>