问题描述:
用几种方式实现元素位于父元素的水平居中位置,如图:
解决
方式一
通过控制子元素的左边框和右边框来达到居中的效果。
在那之前,我先举个我遇到过的错误示范
.father{
background-color: yellow;
width: 300px;
height: 300px;
}
.son{
background-color: red;
width: 100px;
height: 100px;
margin-left:100px;
margin-top: 100px;
}
然后造成的结果如下: 1、发现的问题:子元素没有出现上外边距的效果,反而是父元素出现了上外边距的效果,而子元素的左边框却又有效果。 2、原因:==在默认(标准流)布局的垂直方向上, 默认情况下外边距是不会叠加的, 会出现合并现象, 谁的外边距比较大就听谁的。水平方向上的外边距会叠加。==垂直方向上,这里的父元素没有上补白和上边框,那么它的上边距应该和其文档流中的孩子元素的上边距重叠;而水平方向上,父元素没有左补白和左边距,但其子元素有左边距,而水平方向上父子元素的边距是会叠加的。
那么在设置了子元素外边距的基础上如何让子元素水平居中,有以下几种方式 (1)给父元素设置内边距padding:10px (2)给父元素设置边框border : 1px solid white (3)给父元素设置浮动float:left; (4)给父元素设置overflow:hidden (5)父元素设置相对定位position:reletive;,子元素设置绝对定位position:absolute;
方式二
父相子绝1,子元素中的top和left定位为50%,并且通过改变子元素中的margin-left和margin-top来进行移动,通常均为子元素高宽的一半的负数,也就是让子元素当前位置的相反方向移动。
.father{
background-color: yellow;
width: 300px;
height: 300px;
position: relative;
}
.son{
background-color: red;
width: 100px;
height: 100px;
position:absolute;
top:50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
/*transform: translate(-50%, -50%);*/
/*margin-left和margin-top可以用这个来代替,表示移动自身多少的位置*/
}
分析:当只给父元素和子元素设置边框和背景色的时候,如图: 再此基础上再给父元素设置相对定位,子元素设置绝对定位,并且子元素设置top:50%;left:50%;如图 此时子元素的左上角是出于父元素的正中间的,但子元素的中心并没有处于父元素的中心,所以需要通过改变子元素的左边框和上边框的大小来改变子元素的位置,左右边框设置为margin-left: -50px;margin-top:-50px;,也就是将子元素向左边移动50px的距离,向上移动50px的距离,此时子元素就位于中间了。
方式三
也是采用父相子绝定位,将子元素中的left、right、top、bottom设置为0,通过使用margin:auto让子元素自动调整自身外边框,以便它处于水平居中位置。
.father{
background-color: yellow;
width: 300px;
height: 300px;
position: relative;
}
.son{
background-color: red;
width: 100px;
height: 100px;
position: absolute;
left: 0;
right: 0;
top:0;
bottom: 0;
margin: auto;
}
方式四
使用flex弹性布局,给父元素设置display:flex;,设置其下子元素位于主轴中心justify-content:center,位于交叉轴中心align-items:center;
代码如下:
.father{
background-color: yellow;
width: 300px;
height: 300px;
/* 父元素设置为浮动布局 */
display: flex;
/* 父元素下的子元素位于主轴上的位置为:center */
justify-content: center;
/* 父元素下的子元素位于交叉轴上的位置为:center */
align-items: center;
}
.son{
background-color: red;
width: 100px;
height: 100px;
}
方式五
使用grid布局实现
.outer {
display: grid;
height: 100vh;
}
.inner {
width: 100px;
height: 100px;
align-self: center;
justify-self: center;
background-color: rgb(108, 178, 239);
}
父元素采用相对定位,子元素采用绝对定位 ↩︎