/* 第一種方案 子元素高度可以設(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;引谜。