上又要到秋招的時候了,又有不少人打算換工作了。前端在面試中總會被問到的一道基礎題div居中方法,這里給大家總結一下都有哪些常用的方法。
還未偏移一半自身寬高
<style>
.parent {
position: relative;
width: 500px;
height: 500px;
border: solid red 1px;
}
.demo {
position: absolute;
width: 100px;
height: 100px;
border: solid blue 1px;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
</style>
<body>
<div class="parent">
<div class="demo"></div>
</div>
</body>
通過flex彈性布局設置垂直居中和水平居中
<style>
.parent {
width: 500px;
height: 500px;
border: solid red 1px;
display: flex;
// 垂直,水平居中
align-items: center;
justify-content: center;
}
.demo {
width: 100px;
height: 100px;
border: solid blue 1px;
}
</style>
<body>
<div class="parent">
<div class="demo"></div>
</div>
</body>
在子元素不知道自身寬高情況,使用transform進行比偏移。
<style>
.parent {
position: relative;
width: 500px;
height: 500px;
border: solid red 1px;
}
.demo {
position: absolute;
border: solid blue 1px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
<body>
<div class="parent">
<div class="demo">居中</div>
</div>
</body>
以上3種是常用的方法,當然還有其他居中方法比如grid布局,table-cell布局等。
. 元素高度聲明的情況下在父容器中居中:絕對居中法
<div class="parent">
<div class="absolute-center"></div>
</div>
.parent {
position: relative;
}
.absolute-center {
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
height: 70%;
width: 70%;
}
優點:
1.跨瀏覽器,包括 IE8-10
2.無需其他冗余標記,CSS 代碼量少
3.完美支持圖片居中
4.寬度高度可變,可用百分比
缺點:
1.必須聲明高度
2. 負外邊距:當元素寬度高度為固定值時。設置 margin-top/margin-left 為寬度高度一 半的相反數,top:50%;left:50%
<div class="parent">
<div class="negative-margin-center"></div>
</div>
.parent {
position: relative;
}
.negative-margin-center {
position: absolute;
left: 50%;
top: 50%;
margin-left: -150px;
margin-top: -150px;
height: 300px;
width: 300px;
}
優點:
良好的跨瀏覽器特性,兼容 IE6-7
代碼量少
缺點:
不能自適應,不支持百分比尺寸和 min-/max-屬性設置
內容可能溢出容器
邊距大小域與 padding,box-sizing 有關
3. CSS3 Transform 居中:
<div class="parent">
<div class="transform-center"></div>
</div>
.parent {
position: relative;
}
.transform-center {
position: absolute;
left: 50%;
top: 50%;
margin: auto;
width: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
優點:
內容高度可變
代碼量少
缺點:
IE8 不支持
屬性需要瀏覽器廠商前綴
可能干擾其他 transform 效果
4. table-cell 居中:
法一
#wrap{ position:absolute; width:300px; height:200px; top:50%; left:50%; transform:translate(-50%,-50%) ; background:#009688; } 若是下面的代碼,其結果就是錯誤的
#wrap{ width:300px; height:200px; margin-top:50%; margin-left:50%; transform:translate(-50%,-50%) ; background:#009688; }
原因:
當margin設置成百分數的時候,其top right bottom left的值是參照父元素盒子的寬度進行計算
方法二
直接用彈性盒布局,作用于父元素上實現
*請認真填寫需求信息,我們會在24小時內與您取得聯系。