ITPub博客

首页 > IT职业 > IT图书 > CSS 垂直居中布局

CSS 垂直居中布局

IT图书 作者:lzg215 时间:2021-09-09 09:53:40 0 删除 编辑

下面都是我在网上借鉴的方法,亲测可用。

  //父元素  
 //子元素

第一种: 定位
规则如下:
1、父元素为除了static以外的定位方式;
2、子元素为绝对定位,top、bottom、left和right 均设置为0,margin设置为
auto。
代码如下:

.fStyle {    position: relative;    width: 100px;    height: 100px;    border: 1px solid red;
}.cStyle {    position: absolute;    width: 50px;    height: 50px;    top: 0;    bottom: 0;    left: 0;    right: 0;    margin:auto;    border: 1px solid green;
}

第二种: flex布局
规则如下:align-items实现垂直居中,justify-content实现水平居中。
代码如下:

.fStyle {    width: 100px;    height: 100px;    border: 1px solid red;    display: flex;    align-items: center;    justify-content: center;
}.cStyle {    width: 50px;    height: 50px;    border: 1px solid green;
}

第三种: table-cell布局
规则如下:
1、父布局使用vertical-align: middle实现垂直居中,
2、子布局使用margin: 0 auto实现水平居中。
代码如下:

.fStyle{    width: 100px;    height: 100px;    border: 1px solid red;    display: table-cell;    vertical-align: middle;
}.cStyle{    width: 50px;    height: 50px;    border: 1px solid green;    margin: 0 auto;
}

第四种: translate+relative定位
规则如下:
1、子组件采用relative 定位;
2、top和left偏移各为50%;
3、translate(-50%,-50%) 偏移自身的宽和高的-50%。
代码如下:

.fStyle {    width: 100px;    height: 100px;    border: 1px solid red;
}.cStyle {    width: 50px;    height: 50px;    border: 1px solid green;    position: relative;    top: 50%;    left: 50%;    transform: translate(-50%, -50%);
}



作者:甜甜_饭
链接:https://www.jianshu.com/p/f0771691fa1f


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/420/viewspace-2814121/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: Activity管理类
下一篇: 常用Git操作
请登录后发表评论 登录
全部评论

注册时间:2020-07-23

  • 博文量
    0
  • 访问量
    753