这是我参与更文挑战的第8天,活动详情查看: 更文挑战
方法一 父元素设置:grid栅格布局,align-content: center;justify-content: center; 居中展示
.section-one{
display: grid;
align-content: center;
justify-content: center;
}
.items-one{
background-color: powderblue;
}
方法二: 绝对定位方法:绝对定位下top left right bottom 都设置0 ,magin:auto;
.section-two{
position: relative;
}
.items-two{
width: 100px;
height: 100px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
background-color: yellow;
}
方法三:table-cell实现文字内容水平垂直居中 , 设置好之后margin属性失效
.section-three{
position: relative;
}
.items-three{
background-color: #6495ED;
/* 文字居中展示 */
display: table-cell;
vertical-align: middle;
text-align: center;
position: relative;
top: 100px;
left: 75px;
}
方法四:父元素设置:flex布局,子元素上使用:margin:auto; 居中展示
.section-four{
display: table;
}
.items-foour{
display:table-cell;
vertical-align: middle;
background-color:darkcyan;
}
方法五 :父元素设置:grid栅格布局,子元素 align-self: center; justify-self: center; 居中展示
.section-five{
display: grid;
}
.items-six{
align-self: center;
justify-self: center;
}
方法六:父元素设置:flex布局,子元素上使用:margin:auto; 居中展示
.section-six{
display: flex;
}
.items-six{
background-color: crimson;
margin: auto;
}
方法七: 绝对定位方法:确定当前div的宽度和高度,采用margin值为当前div宽度高度一半的负值
.section-seven{
position: relative;
}
.items-seven{
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
background-color: coral;
}
方法八: flex布局:父元素添加flex样式 ,父元素的宽高要设置*/
.section-eight{
display: flex;
justify-content: center; /* 弹性布局的左右居中对齐 */
align-items: center; /*弹性布局的垂直居中对齐*/
}
.items-eight{
background-color: greenyellow;
}
方法九:绝对定位方法:不确定当前div的宽度和高度,采用 transform: translate(-50%,-50%); 当前div的父级添加相对定位(position: relative;)
.section-nine{
position: relative;
}
.items-nine{
position: absolute;
top: 50%;
left: 50%;
/* translate()函数是css3的新特性.在不知道自身宽高的情况下,可以利用它来进行水平垂直居中 */
transform: translate(-50%,-50%);
background-color: red;
}