说明

对于初学者来说,块级元素的剧中,也是一大难题,我学习的时候,也是一脸懵逼,每次遇到都要百度,但是写的多了也自然记住一些常用的剧中方式,但是还是很模糊,今天就来好好总结一些。

布局

布局即为简单,一个div套着一个div,使inner1在wrap居中显示。

 <body>
<div id="wrap">
<div class="inner1"></div>
</div>
</body>

水平剧中

  • margin: 0 auto;

    子元素的宽度小于父元素,不然子元素宽度等于父元素宽度,就没意义了。

 #wrap{
width: 500px;
height: 500px;
margin: 0 auto;
background-color: red;
} #wrap .inner1{
width: 100px;
height: 100px;
margin: auto;
background-color: blue;
}
  • 绝对定位 + 负外边距

    一开始我也不理解,看图一,当子元素left: 50%;它会以父元素为参照,定位到left值为父元素宽度的一半,如图1的有图,可以看到在将子元素向左移动自身宽度的一半即可水平剧中,因此加上margin-left: 50px;

 #wrap{
width: 500px;
height: 500px;
margin: 0 auto;
position: relative;
background-color: red;
} #wrap .inner1{
width: 100px;
height: 100px;
position: absolute;
left: 50%;
margin-left: -50px;
background-color: blue;
}

  • 绝对定位 + translateX

    上面的方式,有一个缺点,子元素高宽度要知道,但是兼容性好,transform为CSS3新属性,因此有兼容性问题,但是它不需要知道高度值。

 #wrap{
width: 500px;
height: 500px;
margin: 0 auto;
position: relative;
background-color: red;
} #wrap .inner1{
width: 100px;
height: 100px;
position: absolute;
left: 50%;
transform: translateX(-50%);
background-color: blue;
}

垂直居中

  • 绝对定位 + margin: auto 0;

    具体什么原理,我也不是很了解。设置top、bottpm为相同的值,不一定是 0,上下外边距auto即可。

 #wrap{
width: 500px;
height: 500px;
margin: 0 auto;
position: relative;
background-color: red;
} #wrap .inner1{
width: 100px;
height: 100px;
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
background-color: blue;
}
  • 绝对定位 + translateY

    原理与上面的水平居中:绝对得 + translateX的方式一样。

 #wrap{
width: 500px;
height: 500px;
margin: 0 auto;
position: relative;
background-color: red;
} #wrap .inner1{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
transform: translateY(-50%);
background-color: blue;
}

注意

上面只是把水平、垂直居中分开来举例,想要实现水平垂直居中,只要把相应的结合在一起即可。另外我们还可以使用flex布局,实现水平、垂直居中,这里不再讨论了。

  • 绝对定位 + margin实现水平、垂直居中
 //另外一种也如此
#wrap{
width: 500px;
height: 500px;
margin: 0 auto;
position: relative;
background-color: red;
} #wrap .inner1{
width: 100px;
height: 100px;
position: absolute;
//left、top设置为 50%
top: 50%;
left: 50%;
//左、上边距再往回拉自身宽度的一本即可
margin-left: -50px;
margin-top: -50px;
background-color: blue;
}

最新文章

  1. java jdbc的优化之BeanUtils组件
  2. eclipse常见问题
  3. bootstrap-datetimepicker 日期控件的开始日期
  4. BaseAdapter的getView()方法
  5. 《CSS3秘籍》(第三版)-读书笔记
  6. cocos2d3.0跑酷代码讲解和源码
  7. 服务器下自动备份MySQL
  8. 蒙特罗卡π算法(C++语言描述)
  9. P1023 奶牛的锻炼
  10. 浩顺AC671指纹考勤机二次开发(demo)
  11. 查看Linux系统的版本以及位数
  12. 响应式内容滑动插件bxSlider
  13. getBoundingClientRect的用法
  14. 二、Solr单机版的搭建
  15. K好数--蓝桥杯
  16. org.apache.catalina.util.DefaultAnnotationProcessor cannot be cast to org.apache.AnnotationProcessor
  17. Spring Boot 线程池
  18. 网络 --- 1 c/s (b/s)架构 ip 初始socket
  19. c++ 读入优化、输出优化模板
  20. swift3 生成UUID

热门文章

  1. java的package和import机制
  2. Volatile是用于解决什么问题,谈谈实现原理
  3. iptables 添加80端口规则
  4. 洛谷$P3413$ 萌数 $SAC\#1$ 数位$dp$
  5. Android短视频滑动播放(一)
  6. Java防锁屏小程序
  7. NTT 求原根
  8. border-radius属性失效了Ծ‸Ծ
  9. 自定义博客cnblogs样式的必备前端小知识——css
  10. iOS使用fastlane自动化打包到fir(最全最详细流程)