如何將一個div盒子水平垂直都居中?


html代碼如下:

固定樣式:

方法一:利用定位(常用方法,推薦)

.parent{

position:relative;

}

.child{

position:absolute;

top:50%;

left:50%;

margin-top:-50px;

margin-left:-50px;

}

方法一的原理就是定位中心點是盒子的左上頂點,所以定位之后我們需要回退盒子一半的距離。

 

方法二:利用margin:auto;

.parent{

position:relative;

}

.child{

position:absolute;

margin:auto;

top:0;

left:0;

right:0;

bottom:0;

}

方法三:利用display:table-cell;

.parent{

display:table-cell;

vertical-align:middle;

text-align:center;

}

.child{

display:inline-block;

}

方法四:利用display:flex;設置垂直水平都居中;

.parent{

display:flex;

justify-content:center;

align-items:center;

}

方法五:計算父盒子與子盒子的空間距離(這跟方法一是一個道理);

計算方法:父盒子高度或者寬度的一半減去子盒子高度或者寬的的一半。

.child{

margin-top:200px;

margin-left:200px;

}

方法六:利用transform

.parent{

position:relative;

}

.child{

position:absolute;

top:50%;

left:50%;

transform:translate(-50%,-50%);

}

方法七:利用calc計算

.parent{

position:relative;

}

.child{

position:absolute;

top:calc(200px);//(父元素高-子元素高)÷ 2=200px

let:calc(200px);//(父元素寬-子元素寬)÷ 2=200px

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM