如何让一个盒子垂直居中
2017-07-11 00:57
399 查看
方法1:宽度和高度已知的。
思路:
给父元素相对定位
给子元素绝对定位
left: 50%;top: 50%;
margin-left: 负的宽度一半。
margin-top: 负的高度一半;
方法2:宽度和高度自己未知
意思就是说子盒子本身还是有宽度和高度的,只是自己未知。
思路:
给父盒子相对定位
给子盒子绝对定位
top、right、bottom、left全为0
margin: auto;
方法3:flex布局
方法四:平移
思路:
给父元素相对定位
给子元素绝对定位
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>
方法四:平移
<!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>
相关文章推荐
- 如何让一个DIV水平,垂直方向都居中于浏览器?
- 假如有一个固定高度的div,如何让里面的一个图片垂直居中?
- 绝对定位的盒子如何实现水平垂直居中
- 如何让一个div里面的div垂直居中?
- 在一个div内,动态添加一段文字,如何设置为不管内容多少都以 上下垂直居中 的形式展现?
- 如何使一个div在另一个div中绝对居中(水平与垂直方向)
- 如何实现一个img元素在指定容器中水平,垂直居中
- 一个盒子在另一个盒子中垂直居中的方法
- 如何将一个div水平垂直居中?6种方法做推荐
- 如何让一个div里面的div垂直居中?
- 盒子居中 在一个div在父容器div中垂直居中
- 一张图片在一个相应盒子中垂直居中
- 如何将一个div水平垂直居中?4种方法做推荐
- 如何实现一个DIV垂直居中
- 如何让一个DIV水平,垂直方向都居中于浏览器?
- 如何垂直水居中一个元素?
- 公司的一个面试题:如何用css让一个容器水平垂直居中?
- 如何让一个div水平和垂直居中对齐
- 如何让一个div里面的div垂直居中?