总结下我常用的垂直水平居中
来源:互联网 发布:冒泡排序c语言详解 编辑:程序博客网 时间:2024/06/12 21:28
总做中可能会遇到各种需要垂直水平居中的问题,这里总结下我常见的集中。
第一:利用定位position:
1.1在元素宽高已知的情况下,配合负margin达到水平居中
.parent{position:relative}
.child{position:absolute;
top:50%;
left:50%;
width:50px;height:50px:
margin:-25px;
margin-top:-25px
}
<div class="parent" style="background-color: lightgray; width:200px; height:100px; ">
<div class="child" style="background-color: lightblue;">啦啦啦啦</div>
</div>
1.2宽高未知的情况下,利用css3的属性
.parent{position:relative}
.child{position:absolute;
top:50%;
left:50%;
width:50px;height:50px:
transform:translate(-50%,-50%)}
<div class="parent" style="background-color: lightgray; width:200px; height:100px; ">
<div class="child" style="background-color: lightblue;">啦啦啦啦</div>
</div>
1.3利用绝对定位元素的盒模型特性,在偏移属性为确定值的基础上,设置margin:auto.parent{position:relative}
.child{position:absolute;
top:0; bottom:0;
left:0;right:0;
margin:auto
width:50px;height:50px:
}<div class="parent" style="background-color: lightgray; width:200px; height:100px; ">
<div class="child" style="background-color: lightblue;">啦啦啦啦</div>
</div>
第二:渲染成table-cell 之后vertival-align:middle2.1
.parent{
display: table-cell;
text-align: center;
vertical-align: middle;}
.child{
display: inline-block;}
<div class="parent" style="background-color: gray; width:200px; height:100px;">
<div class="child" style="background-color: lightblue;">测试文字</div>
</div>
2.2若若子元素是图像,可不使用table-cell,而是其父元素用行高替代高度,且字体大小设为0。子元素本身设置vertical-align:middle
.parent{
text-align: center;
line-height: 100px;
font-size: 0;}
.child{
vertical-align: middle;}
<div class="parent" style="background-color: gray; width:200px; ">
<img class="child" src="。。。。" width="50%" alt="test">
</div>
第三弹性布局:
3.1在伸缩项目上使用margin:auto
.parent{
display: flex;}
.child{
margin: auto;}
<div class="parent" style="background-color: lightgray; width:200px; height:100px; ">
<div class="child" style="background-color: lightblue;">啦啦啦啦</div>
</div>
3.2在伸缩容器上使用主轴对齐justify-content和侧轴对齐align-items
<style>
.parent{
display: flex;
justify-content: center;
align-items: center;}
<div class="parent" style="background-color: lightgray; width:200px; height:100px; ">
<div class="child" style="background-color: lightblue;">啦啦啦啦</div>
</div>
其实还有很多方法,浮动啊之类的必过没有用过
最后,单行文本垂直水平居中的话就是text-align+line-height了。
- 总结下我常用的垂直水平居中
- 水平居中&垂直居中常用方法总结
- 水平,垂直居中总结
- 常用的水平垂直居中方法
- CSS-水平和垂直居中的总结
- 总结的水平,垂直居中设置方法
- CSS下的水平垂直居中
- CSS的垂直居中和水平居中总结
- 元素水平居中和垂直居中的方式总结
- div下的图片水平居中和垂直居中
- CSS垂直/水平居中总结
- CSS-水平/垂直居中总结
- 垂直居中和水平居中总结
- css垂直水平居中的几种常用方案
- CSS几种常用水平垂直居中的方法
- css开发过程中常用的水平垂直居中
- 各种各样的水平垂直居中
- 元素的水平垂直居中
- Hibernate逆向工程
- hdu 1564 paly a game(博弈论找规律)
- hdu1348 Wall(凸包)
- 调用接口进行天气预报
- LeetCode-Palindrome Linked List
- 总结下我常用的垂直水平居中
- javaEE开发中利用过滤器实现防止中文乱码的问题
- xrwang:【译】随机抽样一致性算法(RANSAC)
- 二叉搜索树转换成双向链表——剑指offer
- 小米笔试-二叉树
- 牛顿法及其下山法+C代码
- 虚拟机上网
- Android广播 ---- BroadcastReceiver
- 【codevs】1703 家族 并查集