CSS布局——DIV水平居中和垂直居中
2016-03-17 15:45
781 查看
DIV水平居中和垂直居中
前言:DIV的水平居中和垂直居中是我们在布局中最常见到的。水平居中应该没有太大的问题,主要对垂直居中做下介绍。1. 嵌套DIV水平居中
HTML Code<div class="parent"> parent <div class="child horizontal-center"> child </div> </div>
CSS Code
/* 水平居中 */ .parent{ width: 50%; height: auto; background: #cccccc; margin: 0 auto; } .child{ padding: 10px; width: 80%; height: auto; background-color: aquamarine; } .horizontal-center{ margin: 0 auto; /* 必须指定宽度 */ }
需要注意的是 margin:? auto; 必须指定其宽度,百分比和数值都OK。
重要的在下面。
2. 嵌套DIV垂直居中
2.1 这里先罗列一下几种DIV垂直居中方法:子DIV容器大小未知:
1.table布局(这里不做介绍)
2.绝对布局+transform
3.flex流布局
4.JS代码+绝对布局(不做介绍)
子DIV容器大小确定(不做介绍):
1.子DIV margin
2.父级DIV padding
3.绝对布局
2.2 绝对布局+transform 实现DIV垂直居中
HTML Code
<div class="parent"> parent <div class="child"> child </div> </div>
CSS Code
.parent{ width: 50%; height: 200px; background: #cccccc; margin: 0 auto; position: relative; } .child{ position: absolute; left: 50%; top:50%; height: 20%; width: 50%; transform: translateX(-50%) translateY(-50%); background-color: aquamarine; }
这里采用绝对布局先使子DIV 代码:top:50% ,因为子DIV有高度,所以再往回移动子DIV高度的50% 代码:transform: translateY(-50%); 至此完成垂直居中的操作。这种做法简单 ,但是只支持IE9+以及IE9。
注意:曾在网上看到用margin的方法代替transform的 ,亲自测试了一下。发现不行,原因呢? 是margin-top/margin-bottom 按百分比来计算的话,是按width来计算的并不是height,所以自然无法实现了。具体这种做法是为什么?有兴趣的可以上知乎看看。
2.3 flex 流布局
HTML Code
<div class="parent vertical-container"> parent <div class="child "> child </div> </div>
CSS Code
.parent{ width: 50%; height: 200px; background: #cccccc; margin: 0 auto; } .child{ height: 50%; width: 60%; background-color: aquamarine; } .vertical-container{ display: -webkit-flex; display: flex; -webkit-align-items: center; align-items: center; -webkit-justify-content: center; justify-content: center; }
注意:父级的文字也居中了
Flex 流布局和BootStrap的栅格布局功能类似。这种方法很好,兼容性好像也只支持IE9+,其他主流浏览器基本都支持。
这篇是阮一峰的讲解 Flex 布局教程:语法篇 内容十分详细 ,非常不错。
3.总结
当然还有文字居中,背景图居中等等。以上还有几种方法没有介绍。希望以后自己能修改并补充。
flex布局 感觉用的很舒服啊 。嗯。加油加油 ,多去学习别人的方法。
相关文章推荐
- Web布局连载——两栏固定布局(五)
- [div+css]晒晒最新制作专题推广页模板
- 盒子模型
- CSS选择器
- CSS样式优先权
- [css] line-height 百分比单位和数值单位的区别
- Apple官网研究之使用Justify布局导航
- 设计更快的网页(三):字体和 CSS 调整
- 纯CSS制作的新闻网站中的文章列表
- 10条影响CSS渲染速度的写法与使用建议第1/3页
- BS项目中的CSS架构_仅加载自己需要的CSS
- 很不错的 CSS Hack 又学了一招
- 发一个css比较清爽的写法
- CSS expression控制图片自动缩放效果代码[兼容 IE,Firefox]
- css布局网页水平居中常用方法
- CSS经典技巧十则第1/2页
- css 兼容性问题this.style.cursor=''hand''
- IE6不能正常解析CSS文件问题的解决方法及原因分析
- 欲练CSS ,必先解决IE的一些细节分析
- CSS文字截取功能实现代码