当前位置: 首页 > Web前端 > HTML5

CSS-CSS3实现居中(水平&垂直)

时间:2023-04-05 23:29:12 HTML5

1、水平居中:内联元素将内联元素放在一个属性块(display:block)元素中,然后设置父层元素属性居中:.test{text-align:center;}2、水平居中:块元素设置Margin.test{margin:100pxauto;}3、水平居中:多个块元素设置块元素属性(display:inline-block),然后设置父层元素属性居中:.test{text-align:center;}4.水平居中:多个块元素(flexbox布局实现)设置块元素的父元素属性display:flex和justify-content:center如下:.test{text-align:center;}5、Vertical居中:为单行内联元素设置height和line-height属性。test{height:100px;line-height:100px;}6、垂直居中:为多行内联元素设置display:table-cell为父元素becenteredandvertical-align:middleattribute.test{background:red;width:200px;height:200px;/*以下属性垂直居中*/display:table-cell;vertical-align:middle;}7、verticalcentering:Known高度块元素为要居中的元素设置以下属性。测试{top:50%;margin-top:-50px;/*margin-top值为自身高度的一半*/position:absolute;padding:0;}8.水平居中和垂直居中:对于已知高宽的元素,设置元素居中的如下属性(1).test{position:absolute;margin:auto;left:0;top:0;right:0;bottom:0;}(2).test{position:absolute;top:50%;left:50%;margin-顶部:-75px;/*设置margin-left/margin-top为自身高度的一半*/margin-left:-75px;}9、水平和垂直居中:未知高度和宽度的元素为要居中的元素设置以下属性.test{位置:absolute;top:50%;left:50%;transform:translate(-50%,-50%);/*使用css3的transform实现*/}10、水平和垂直居中:可以使用flex设置如下属性.test{display:flex;justify-content:center;align-items:center;/*注意需要在这里设置高度才能看到垂直居中的效果*/background:#AAA;height:300px;}