css实现水平垂直居中的几种方法
2017-05-30 18:44
926 查看
先约定初始化的父元素、子元素
1、绝对定位居中。
2、相对定位绝对定位和负边距。
3、弹性布局,适合宽度高度未知的情况,但是要注意兼容性。
4、css3的transform,适合高度宽度未知的情况。
5、分别对父盒子、子盒子使用display:table-cell,inline-block,适合高度宽度未知的情况。
6、另外,对于文字或图片而言( inline元素 ):
水平居中:text-align:center;
垂直居中:display:table-cell; vertical-align:middle;
或者,配合line-height;
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>css实现水平垂直居中的几种方法</title> <style> #container{ width: 400px; height: 400px; position: relative; background: #CCC; margin:0 auto; } #box{ width: 200px; height: 200px; background: #F00; position:absolute; } </style> </head> <body> <div id="container"> <div id="box">我是一行文字</div> </div> </body> </html>
1、绝对定位居中。
#container{ width: 400px; height: 400px; position: relative; background: #CCCCCC; margin:0 auto; overflow:auto; /*可不加,防止内容溢出 */ } #box{ width: 200px; height: 200px; background: #F00; position: absolute; margin: auto; left: 0; top: 0; right: 0; bottom: 0; }
2、相对定位绝对定位和负边距。
#container{ width: 400px; height: 400px; position: relative; background: #CCCCCC; margin: 0 auto; } #box{ width: 200px; height: 200px; background: #F00; position: absolute; left: 50%; top: 50%; margin: -100px 0 0 -100px; }
3、弹性布局,适合宽度高度未知的情况,但是要注意兼容性。
#container{ width: 400px; height: 400px; position: relative; background: #CCCCCC; margin: 0 auto; display: flex; justify-content: center; /*项目在主轴方向上对齐 */ align-items: center; /*项目在交叉轴方向上对齐 */ } #box{ width: 200px; height: 200px; background: #F00; position: absolute; }
4、css3的transform,适合高度宽度未知的情况。
#container{ width: 400px; height: 400px; position: relative; background: #CCCCCC; margin: 0 auto; } #box{ width: 200px; height: 200px; background: #F00; position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%);/* 根据自身高宽度位移*/ }
5、分别对父盒子、子盒子使用display:table-cell,inline-block,适合高度宽度未知的情况。
#container{ width: 400px; height: 400px; /*position: relative;*/ background: #CCCCCC; margin: 0 auto; display: table-cell; text-align: center; vertical-align:middle; } #box{ width: 200px; height: 200px; background: #F00; /*position: absolute;*/ display: inline-block; }
6、另外,对于文字或图片而言( inline元素 ):
水平居中:text-align:center;
垂直居中:display:table-cell; vertical-align:middle;
或者,配合line-height;
相关文章推荐
- 用css实现垂直水平居中的几种方法
- CSS实现水平垂直居中的几种方法
- 使用纯CSS实现未知尺寸的图片(但高宽都小于500px)在500px的正方形容器中水平和垂直居中。你有几种方法?
- css实现水平、垂直居中的几种方法
- 【css】实现垂直水平居中的几种方法
- CSS实现垂直居中的几种方法
- css 水平居中垂直居中的几种方法
- css 垂直居中的几种实现方法
- [转载]CSS实现垂直居中的几种方法
- 实现div水平、垂直居中的几种方法
- CSS实现元素水平、垂直居中的方法
- css 实现元素水平垂直居中总结5中方法
- 使图片垂直&水平居中的CSS实现方法
- css居中的实现方法(包括水平居中和垂直居中)
- CSS实现垂直居中的几种方法
- CSS实现元素水平/垂直居中的方法
- 纯CSS实现垂直居中的几种方法
- CSS实现垂直居中的几种方法
- CSS实现垂直居中的几种方法
- css水平垂直居中三种实现方法