html
<div class="box"> <div class="box1"></div> </div>
方法一:要求子元素固定宽高
绝对定位的百分比是相对于父元素的宽高,通过这个特性可以让子元素居中显示,
但绝对定位是基于子元素的左上角,期望的效果是子元素的中心居中显示。
为了修正这个问题,可以借助外边距的负值,负的外边距可以让元素向相反方向定位,
通过指定子元素的外边距为子元素宽度一半的负值,就可以让子元素居中了
css
.box { position: relative; border: 1px solid red; width: 300px; height: 300px; margin: 50px auto; } .box1 { position: absolute; top: 50%; left: 50%; margin-left: -50px; margin-top: -50px; width: 100px; height: 100px; background-color: yellow; }
方法二: 要求子元素固定宽高
absolute + margin auto
通过设置各个方向的距离都是 0,此时再讲 margin 设为 auto,就可以在各个方向上居中了
css
.box { position: relative; width: 300px; height: 300px; margin: 50px auto; border: 1px solid red; } .box1 { position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; width: 100px; height: 100px; background-color: yellow; }
方法三:要求子元素固定宽高
calc() 函数用于动态计算长度值,运算符前后都需要保留一个空格,例如:width: calc(100% - 10px)
top 的百分比是基于元素的左上角,那么在减去宽度的一半就好了
依赖 calc 的兼容性,css3新加属性,兼容性不好
css
.box { position: relative; width: 300px; height: 300px; margin: 50px auto; border: 1px solid red; } .box1 { position: absolute; top: calc(50% - 50px); left: calc(50% - 50px); width: 100px; height: 100px; background-color: yellow; }
方法四:不需要子元素固定宽高
absolute + transform
css3 新增的 transform,transform 的 translate 属性也可以设置百分比,其是相对于自身的宽和高
transform 属性向元素应用 2D 或 3D 转换,translate(x,y) 定义 2D 转换。
css
.box { position: relative; width: 300px; height: 300px; margin: 50px auto; border: 1px solid red; } .box1 { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 100px; height: 100px; background-color: yellow; }
方法五: 要求子元素固定宽高
把 box 设置为行内元素,通过 text-align 就可以做到水平居中,
vertical-align 也可以在垂直方向做到居中,子元素中将文字显示重置为想要的效果
vertical-align 属性设置元素的垂直对齐方式 , middle把此元素放置在父元素的中部
css
.box { width: 300px; height: 300px; line-height: 300px; text-align: center; margin: 50px auto; border: 1px solid red; } .box1 { display: inline-block; vertical-align: middle; width: 100px; height: 100px; background-color: yellow; }
方法六:
css 新增的 table 属性,可以让我们把普通元素,变为 table 元素的现实效果,通过这个特性也可以实现水平垂直居中
vertical-align 属性设置元素的垂直对齐方式 , middle把此元素放置在父元素的中部。
css
.box { display: table-cell; text-align: center; vertical-align: middle; width: 300px; height: 300px; border: 1px solid red; } .box1 { display: inline-block; width: 100px; height: 100px; background-color: yellow; }
方法七:flex
justify-content 属性定义flex子项在flex容器的当前行的主轴(横轴)方向上的对齐方式
align-items 属性定义flex子项在flex容器的当前行的侧轴(纵轴)方向上的对齐方式
css
.box { display: flex; justify-content: center; align-items: center; width: 300px; height: 300px; margin: 50px auto; border: 1px solid red; } .box1 { width: 100px; height: 100px; background-color: yellow; }
方法八:grid
它将网页划分成一个个网格,可以任意组合不同的网格,做出各种各样的布局,兼容性不太好
align-self 属性定义flex子项单独在侧轴(纵轴)方向上的对齐方式
justify-self 属性定义flex子项单独在主轴(横轴)方向上的对齐方式
css
.box { display: grid; width: 300px; height: 300px; margin: 50px auto; border: 1px solid red; } .box1 { align-self: center; justify-self: center; width: 100px; height: 100px; background-color: yellow; }
css中如何使div元素居中垂直水平居中
最新推荐文章于 2024-07-24 11:16:38 发布