html块级元素的水平垂、直居中的方式
2024-09-06 17:32:04
说明
对于初学者来说,块级元素的剧中,也是一大难题,我学习的时候,也是一脸懵逼,每次遇到都要百度,但是写的多了也自然记住一些常用的剧中方式,但是还是很模糊,今天就来好好总结一些。
布局
布局即为简单,一个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;
}
最新文章
- java jdbc的优化之BeanUtils组件
- eclipse常见问题
- bootstrap-datetimepicker 日期控件的开始日期
- BaseAdapter的getView()方法
- 《CSS3秘籍》(第三版)-读书笔记
- cocos2d3.0跑酷代码讲解和源码
- 服务器下自动备份MySQL
- 蒙特罗卡π算法(C++语言描述)
- P1023 奶牛的锻炼
- 浩顺AC671指纹考勤机二次开发(demo)
- 查看Linux系统的版本以及位数
- 响应式内容滑动插件bxSlider
- getBoundingClientRect的用法
- 二、Solr单机版的搭建
- K好数--蓝桥杯
- org.apache.catalina.util.DefaultAnnotationProcessor cannot be cast to org.apache.AnnotationProcessor
- Spring Boot 线程池
- 网络 --- 1 c/s (b/s)架构 ip 初始socket
- c++ 读入优化、输出优化模板
- swift3 生成UUID