要在不使用Flex布局的情况下实现子元素在父元素中固定居中显示,可以使用以下几种方法:
这种方法适用于已知子元素的尺寸。
.parent {
position: relative;
width: 100%;
height: 100vh; /* 父元素的高度 */
}
.child {
position: absolute;
top: 50%;
left: 50%;
width: 200px; /* 子元素的宽度 */
height: 100px; /* 子元素的高度 */
margin-top: -50px; /* 负边距为子元素高度的一半 */
margin-left: -100px; /* 负边距为子元素宽度的一半 */
}
transform
这种方法不需要知道子元素的尺寸。
.parent {
position: relative;
width: 100%;
height: 100vh; /* 父元素的高度 */
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
这种方法适用于需要兼容旧版浏览器的情况。
.parent {
display: table;
width: 100%;
height: 100vh; /* 父元素的高度 */
}
.child {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child-inner {
display: inline-block;
}
虽然你提到不使用Flex布局,但如果你愿意使用CSS Grid布局,这也是一个不错的选择。
.parent {
display: grid;
place-items: center;
width: 100%;
height: 100vh; /* 父元素的高度 */
}
.child {
/* 子元素的样式 */
}
margin: auto
和绝对定位这种方法适用于已知父元素的尺寸。
.parent {
position: relative;
width: 100%;
height: 100vh; /* 父元素的高度 */
}
.child {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
width: 200px; /* 子元素的宽度 */
height: 100px; /* 子元素的高度 */
}
根据你的具体需求选择合适的方法。