子元素在父元素中居中
以class名为parent的父元素400400px, class名为child的子元素200200px为例子
<div class="parent">
<div class="child"></div>
</div>
水平居中
方法一:
描述:
子元素设置margin:auto
css代码如下:
.parent {
width: 400px;
height: 400px;
background: #ccc;
.child {
width: 200px;
height: 200px;
background: #eee;
margin: auto;
}
}
运行截图如下:
方法二:
描述:将子元素设置成display: inline-block;,父元素设置text-align: center;
运用知识点:
display:block
block元素会独占一行,多个block元素会各自新起一行。默认情况下,block元素宽度自动填满其父元素宽度。
block元素可以设置width,height属性。块级元素即使设置了宽度,仍然是独占一行。
block元素可以设置margin和padding属性。
display:inline
inline元素不会独占一行,多个相邻的行内元素会排列在同一行里,直到一行排列不下,才会新换一行,其宽度随元素的内容而变化。
inline元素设置width,height属性无效。
inline元素的margin和padding属性,水平方向的padding-left, padding-right, margin-left, margin-right都产生边距效果;但竖直方向的padding-top, padding-bottom, margin-top, margin-bottom不会产生边距效果。
display:inline-block
简单来说就是将对象呈现为inline对象,但是对象的内容作为block对象呈现。之后的内联对象会被排列在同一行内。比如我们可以给一个link(a元素)inline-block属性值,使其既具有block的宽度高度特性又具有inline的同行特性。
代码如下:
.parent {
width: 400px;
height: 400px;
background: #ccc;
text-align: center;
.child {
width: 200px;
height: 200px;
background: #eee;
display: inline-block;
}
}
截图如上图
水平垂直居中
方法一:
描述:子元素相对于父元素绝对定位,子元素top、left设置成50%,margin-top、margin-left减去子元素自身的一半
.parent {
width: 400px;
height: 400px;
background: #ccc;
position: relative;
.child {
width: 200px;
height: 200px;
background: #eee;
position: absolute;
left: 50%;
top: 50%;
margin-top: -100px;
margin-left: -100px;
}
}
方法二:
描述:子元素相对于父元素句对定位,子元素top、left设置成50%,tranform:translate(-50%, -50%)
.parent {
width: 400px;
height: 400px;
background: #ccc;
position: relative;
.child {
width: 200px;
height: 200px;
background: #eee;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
}
方法三:
描述:子元素相对于父元素绝对定位,子元素上下左右都设为0,margin:auto
.parent {
width: 400px;
height: 400px;
background: #ccc;
position: relative;
.child {
width: 200px;
height: 200px;
background: #eee;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
}
方法四:
描述:子元素设为相对定位,子元素top、left设为50%,tranform:translate(-50%,-50%)
.parent {
width: 400px;
height: 400px;
background: #ccc;
position: relative;
.child {
width: 200px;
height: 200px;
background: #eee;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
}
方法五:
描述:利用弹性盒,父元素设置成弹性盒
.parent {
width: 400px;
height: 400px;
background: #ccc;
display: flex;
justify-content: center;
align-items: center;
.child {
width: 200px;
height: 200px;
background: #eee;
}
}
运行截图如下: