css:盒子垂直水平居中的几种方法
2018-02-28 08:40
549 查看
方法1:宽度和高度已知的。
思路:给父元素相对定位
给子元素绝对定位
left: 50%;top: 50%;
margin-left: 负的宽度一半。
margin-top: 负的高度一半;
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>居中</title> <style type="text/css"> #box{ width: 400px; height: 200px; position: relative; background: red; } #box1{ width: 200px; height: 100px; position: absolute; top: 50%; left: 50%; margin-left: -100px; margin-top: -50px; background: green; } </style> </head> <body> <div id="box"> <div id="box1"> </div> </div> </body> </html>
方法2:宽度和高度自己未知
意思就是说子盒子本身还是有宽度和高度的,只是自己未知。思路:
给父盒子相对定位
给子盒子绝对定位
top、right、bottom、left全为0
margin: auto;
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>居中</title> <style type="text/css"> #box{ width: 800px; height: 400px; position: relative; background: red; } #box1{ width: 100px; height: 50px; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; background: green; } </style> </head> <body> <div id="box"> <div id="box1"> </div> </div> <script type="text/javascript"> </script> </body> </html>
方法3:flex布局
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>垂直居中</title> <style type="text/css"> .box{ width: 400px; height: 200px; background: #f99; } .box1{ width: 200px; height: 100px; background: green; } .center{ display: flex; justify-content: center;//实现水平居中 align-items: center;//实现垂直居中 } </style> </head> <body> <div class="box center"> <div class="box1"> </div> </div> </body> </html>
方法四:平移 定位+transform
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>css3让一个盒子居中</title> <style type="text/css"> .parent_box{ width: 400px; height: 200px; background: red; position: relative; } .child_box{ width: 200px; height: 100px; background: #9ff; position: absolute; top: 50%; left: 50%; transform: translate( -50%,-50%); } </style> </head> <body> <div class="parent_box"> <div class="child_box"> </div> </div> </body> </html>
方法五:table-cell布局
父级 display: table-cell; vertical-align: middle; 子级 margin: 0 auto;**水平方向的居中
再加一种水平方向上居中 :margin-left : 50% ; transform: translateX(-50%);相关文章推荐
- css 几种水平垂直居中的方法 及 弹性盒子
- css几种方法使元素水平垂直居中
- CSS水平垂直居中的几种方法
- CSS水平垂直居中的几种方法
- css实现水平垂直居中的几种方法
- div盒子在页面中水平垂直居中的几种方法。
- CSS水平垂直居中的几种方法
- CSS实现水平垂直居中的几种方法
- 用css实现垂直水平居中的几种方法
- CSS实现垂直居中的常用方法 在前端开发过程中,盒子居中是常常用到的。其中 ,居中又可以分为水平居中和垂直居中。水平居中是比较容易的,直接设置元素的margin: 0 auto就可以实现。但是垂直
- css的几种垂直水平居中方法
- CSS水平垂直居中的几种方法
- 关于css垂直水平居中的几种方法
- CSS水平垂直居中的几种方法2
- CSS水平垂直居中的几种方法
- 使用纯CSS实现未知尺寸的图片(但高宽都小于500px)在500px的正方形容器中水平和垂直居中。你有几种方法?
- html中div如何水平和垂直居中的几种css方法代码
- CSS几种常用水平垂直居中的方法
- CSS水平垂直居中的几种方法
- css实现水平、垂直居中的几种方法