解决方法一:使用flex布局
HTML代码示例:
Div 1
Div 2
CSS代码示例:
.container {
display: flex;
justify-content: center;
align-items: flex-start;
}
.div1 {
width: 200px;
height: 100px;
background-color: red;
}
.div2 {
width: 300px;
height: 200px;
background-color: blue;
}
解决方法二:使用绝对定位和transform属性
HTML代码示例:
Div 1
Div 2
CSS代码示例:
.container {
position: relative;
}
.div1 {
width: 200px;
height: 100px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.div2 {
width: 300px;
height: 200px;
background-color: blue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
以上两种方法都可以实现不同大小的div相对于顶部居中。方法一使用了flex布局的属性,方法二使用了绝对定位和transform属性。可以根据具体情况选择适合的解决方法。