絕對定位元素水平垂直居中的兩種常見方法
一、負外邊距
方法:絕對定位元素的尺寸已知,top設置為50%,left設置為50%,外邊距margin取負數,大小是寬度width和高度height的一半,有內邊距padding時要加上padding值再取半。具體代碼如下:
html代碼:
<div >
<div ></div>
</div>
css代碼:
.box{
position: relative;
width: 200px;
height: 200px;
background: yellow;
}
.box1{
position: absolute;
top: 50%;
left:50%;
background: red;
width: 100px;
height: 100px;
padding: 10px;
margin-top: -60px;
margin-left: -60px;
}
瀏覽器顯示如下:
除了這種常用方法外,在網上還看到了另一種比較簡便的方法,整理如下:
二、利用margin: auto實現居中
方法:設置絕對定位元素top和bottom的值相等,left和right的值相等。但是left和right的值不能超過其相對元素width減去它自身width的一半,否則絕對定位會優先選取left值進行定位。top和bottom無此限製。最好配合overflow:auto防止溢出。具體代碼如下:
css代碼:
.box1{
position: relative;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: 100px;
height: 100px;
background: red;
overflow: auto;//當內部內容較多時,會自動出現滾動條
}
瀏覽器顯示同上。
最後更新:2017-08-23 13:02:20