花式居中

水平居中

1.行内元素居中
/*html*/
 

xixixixi

/*css*/ p{ text-align: center }
2.块级元素
  • 普通版
/*html*/
/*css*/ div{ width: 100px; height: 100px; margin: 0 auto; }
  • 升级版
//flex布局
/*html*/
/*css*/ #container > div{ width: 100px; height:100px; background-color: #7f7f7f; } #container{ display:flex; justify-content: center; }
//多个块级元素的水平居中
/*html*/
/*css*/ #container{ text-align: center; } #container > div{ width: 100px; height:100px; background-color: #7f7f7f; display: inline-block; }

垂直居中

1.行内元素
  • 普通版
/*html*/

xixixixi

/*css*/ #container { height: 100px; background-color: #7f7f7f; } p { line-height: 100px; height: 100px; }
  • 升级版
//多行行内元素
/*HTML*/

xixixixi

heihiehiehei

hhhhhh

/*css*/ #container { height: 1000px; background-color: #7f7f7f; display: table-cell; vertical-align: middle; }
2.块级元素
//已知高度
/*HTML*/
/*CSS*/ #container { border: 1px solid;//解决父元素与子元素边距折叠问题 height: 200px; background-color: #7f7f7f; } #container > div { height: 100px; margin-top: 50px; background-color: #0074D9; }
//未知高度
/*HTML*/
5555
/*CSS*/ #container { display: flex; height: 200px; background-color: #7f7f7f; align-items: center; }

水平垂直居中

1.已知高度
/*HTML*/
/*CSS*/ div{ background-color: #7f7f7f; width: 100px; height: 100px; position: absolute; margin: auto; top: 0; left: 0; bottom: 0; right: 0; }
2.未知高度
/*HTML*/
/*CSS*/ //方法一 div{ background-color: #7f7f7f; width: 100px; height: 100px; position: absolute; top: 50%; left: 50%; margin-top: -50px; margin-left: -50px; } //方法二 div{ background-color: #7f7f7f; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%);//相对于自身偏移,负值为左上 }
//flex布局
/*HTML*/
xixixi
/*CSS*/ #c { background-color: #7f7f7f; height: 100px; display: flex; justify-content: center; align-items: center; }

你可能感兴趣的:(花式居中)