CSS水平垂直居中方案 包括Grid方案

/* 第一種方案 子元素高度可以設(shè)定也可以不設(shè)定*/

.app{

? ? width: 500px;

? ? height: 500px;

? ? background: greenyellow;

? ? display: flex;

? ? align-items: center;

? ? justify-content: center;


}

.app>div{

? ? width: 100px;

? ? height: 100px;

? ? font-size: 20px;

? ? background: blueviolet;

}

/* 第二種方案 子元素高度可以設(shè)定也可以不設(shè)定*/

.app{

? ? width: 500px;

? ? height: 500px;

? ? background: greenyellow;

? ? position: relative;


}

.app>div{

? ? width: 100px;

? ? height: 100px;

? ? font-size: 20px;

? ? background: blueviolet;

? ? position: absolute;

? ? top: 0;

? ? left: 0;

? ? right: 0;

? ? bottom:0;

? ? margin: auto;

}

/* 第三種方案 子元素高度可以設(shè)定也可以不設(shè)定*/

.app{

? ? width: 500px;

? ? height: 500px;

? ? background: greenyellow;

? ? position: relative;


}

.app>div{

? ? width: 100px;

? ? height: 100px;

? ? font-size: 20px;

? ? background: blueviolet;

? ? position: absolute;

? ? top: 50%;

? ? left: 50%;

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

}

/* 第四種方案 高度就是文字加line-height的高度 局限性在于必須里邊的元素是inline否則不生效*/

.app{

? ? width: 500px;

? ? height: 500px;

? ? background: greenyellow;

? ? line-height: 500px;

? ? text-align: center;


}

.app>div{

? ? width: 100px;

? ? font-size: 20px;

? ? background: blueviolet;

? ? display: inline;

}

/* 第五種方案 橫向利用margin auto,垂直還是利用定位和平移 也不用管里邊元素的高度*/

.app{

? ? width: 500px;

? ? height: 500px;

? ? background: greenyellow;

}

.app>div{

? ? width: 100px;


? ? font-size: 20px;

? ? background: blueviolet;

? ? position: relative;

? ? top: 50%;

? ? transform: translateY(-50%);

? ? margin-left: auto;

? ? margin-right:auto ;

}

/* 第六種方案 grid方案*/

.container {display:grid;place-items:center;}

上面代碼需要寫在容器上,指定為 Grid 布局。核心代碼是place-items屬性那一行,它是一個(gè)簡寫形式。

place-items:<align-items><justify-items>;

align-items屬性控制垂直位置,justify-items屬性控制水平位置。這兩個(gè)屬性的值一致時(shí),就可以合并寫成一個(gè)值。所以,place-items: center;等同于place-items: center center;。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容