css布局之居中
来源:互联网 发布:shadow web 黑暗网络 编辑:程序博客网 时间:2024/04/30 21:32
在css中,居中是很常用的事情,因为大多数人都喜欢一种对称的美。对于居中来说,有的一个属性就可以解决,有的就需要一点技巧。我在之前的一片博客里写到了绝对定位的居中,不过那只是其中的一小部分。
先来一些人畜无害,简单的居中方法。
对于水平居中来说:
一,把margin设为auto
这种方法在使用的时候,需要把margin-left和margin-right设为auto,可以实现水平居中,但是只能适用于块级元素,而且对于浮动元素和绝对定位不适用。
二,设置text-align:center
这个属性只能对一些行内元素使用,即display为inline或者inline-block的才使用。
三,使用绝对定位来居中
原理是先让元素向右移动50%的距离,这个时候左边框正好在中间的位置,然后再向左移动元素宽度一般的距离,就可以使其居中。
<style type="text/css"> .box{ width:500px; height:300px;; margin-left:-250px; position:relative/absolute; left:50%; top:50%; background-color: #cc18b9; }<div class="box"> </div>四,另一种使用绝对定位来居中的方法
<style type="text/css"> .box{ width:500px; height:300px; position:absolute; left:0; top:0; bottom:0; right:0; margin:auto auto; background-color: #cc18b9; }<div class="box"> </div>特别需要注意的就是这个方法,如果要水平居中,需要把left和right都设置为0,然后margin-left和margin-right都设置为auto;如果需要垂直居中,可以采用同理的方法。
对于垂直居中:
一,对行级元素居中
使line-height与父级元素的height一致。
二,对块级元素居中
1,首先直接使line-height和父级的height相等。
2,然后使用display:inline|inline-block,vertical-align:midden。
.box { width: 200px; height: 200px; border: 1px solid skyblue; line-height: 200px; } .box2 { width: 100px; height: 100px; display: inline-block; vertical-align: middle; background: hotpink; }<div class="box"> <div class="box2"></div></div>三,对于父元素高度不确定的
父元素的padding-top和padding-bottom一样 。
1 0
- css布局之居中
- css之居中布局
- CSS布局之各种居中
- 解读CSS布局之-水平垂直居中
- CSS布局学习笔记之图片居中
- CSS布局之水平垂直居中
- css布局之水平垂直居中
- 解读CSS布局之-水平垂直居中
- CSS布局之水平垂直居中
- 解读 CSS 布局之水平垂直居中
- CSS布局之-水平垂直居中
- CSS布局奇葩技巧之--各种居中
- CSS布局技巧之--各种居中
- CSS布局技巧之--各种居中
- CSS布局技巧之--各种居中
- 解读 CSS 布局之水平垂直居中
- 解读 CSS 布局之水平垂直居中
- CSS布局技巧之–各种居中
- Asp.net MVC 中Controller返回值类型ActionResult
- 关联表查询,行转列
- spring源码学习之六 </property-placeholder>元素处理过程
- 大数据概述1
- KCF(核化相关滤波)跟踪公式推导笔记(2)——非线性滤波器的解、快速检测及快速核相关
- css布局之居中
- RESTful API 设计最佳实践
- Java 静态与非静态方法的区别
- [BZOJ3626][LNOI2014]LCA(离线+链剖)
- xcode 低版本 要运行 iOS高的系统 真机测试
- C#中用HttpWebRequest中发送GET/HTTP/HTTPS请求
- 贝叶斯方法(Bayesian approach) —— 一种概率解释(probabilistic interpretation)
- OC 对象的内存存储细节(类方法及对象方法的调用细节)
- RTP协议分析