使一个不定宽高的盒子实现垂直水平居中(简单) 您所在的位置:网站首页 盒子怎样居中 使一个不定宽高的盒子实现垂直水平居中(简单)

使一个不定宽高的盒子实现垂直水平居中(简单)

2024-02-02 16:12| 来源: 网络整理| 查看: 265

如何使一个不定宽高的元素实现垂直水平居中

结构

1.使用css方法:

父盒子设置:display:tbale-cell; text-align:center; vertical-align:middle;

子元素设置:dislplay: inline-block; vertical-align:middle;

.father { display:tbale-cell; text-align:center; vertical-align:middle; background-color: antiquewhite; } .son { dislplay: inline-block; vertical-align:middle; background-color: bisque; } 属性:display:tbale-cell; 1.使元素表现出类似td的效果,可以使不固定大小的元素出现垂直居中的效果2.不要与 float:left; position:absolute;一起使用3.magin设置无效,可以响应padding设置4.该属性对宽度和高度比较敏感5.不要对display:tbale-cell使用百分比设置宽度和高度 2.使用css3的 transform:

父盒子设置:dispaly: relative;

子盒子设置:transform: translate(-50%,-50%); position: absolute; top:50%; left:50%;

.father { dispaly: relative; background-color: antiquewhite; } .son { position: absolute; top:50%; left:50%; transform: translate(-50%,-50%); background-color: bisque; } 3.让父盒子为flex容器: .father { width: 200px; height: 100px; background-color: antiquewhite; /* 设置父项 */ display: flex; /* 设置子元素在主轴上的排列方式 */ justify-content: center; /* 设置子元素在侧轴的排列方式(单行排列方式) */ align-items: center; } .son { width: 100px; height: 40px; background-color: bisque; } 4.实现绝对定位元素的水平方向居中:margin: auto; .father { width: 300px; height: 100px; background-color: aquamarine; position: relative; } .son { width: 46px; height: 40px; background-color: bisque; position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; }


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有