我有两个已知宽度和高度的盒子(div),并希望将它们放入正文中,并满足以下要求。让这些盒子调用 box1
和 box2
。
1)两个框都应垂直居中。
2) 两个盒子都应水平放置,以便它们重叠,并且 box1
保持在 box2
外部 50%。
3) box1
+ box2
应水平居中
我已经为此编写了代码并实现了第一个和第二个,但无法实现第三个。
https://jsfiddle.net/02o2h6gp/1/
html代码
<body>
<div class="content">
<div class="boxes-container">
<div class="box1"></div>
<div class="box2"></div>
</div>
</div>
</body>
CSS部分
html {
height: 100%;
}
body {
background-image: -webkit-linear-gradient(blue, white);
background-image: -moz-linear-gradient(blue, white);
background-image: -o-linear-gradient(blue, white);
background-image: linear-gradient(blue, white);
display: flex;
flex-direction: column;
justify-content: center;
height: 100%;
}
.content{
display: flex;
flex-direction: row;
justify-content: center;
}
.boxes-container {
display: flex;
flex-direction: row;
/*justify-content: center;*/
margin: auto;
}
.box1 {
background: blue;
box-shadow: 0 60px 80px 0 rgba(0,0,0,0.30);
border-radius: 10px;
width: 400px;
height: 271px;
margin: auto;
transform: translateX(50%);
}
.box2 {
background: #FFFFFF;
box-shadow: 0 60px 80px 0 rgba(0,0,0,0.30);
border-radius: 10px;
width: 740px;
height: 586px;
margin: auto;
/*transform: translateX(-30%);*/
z-index: -1;
}
最佳答案
- 无需在 x 轴上平移 box1 50%,只需在 x 轴上平移 box1 25%,在 x 轴上平移 box-25%。这样两边的空间就相等。
- 将align-content: center添加到.boxes-container。
html {
height: 100%;
}
body {
background-image: -webkit-linear-gradient(blue, white);
background-image: -moz-linear-gradient(blue, white);
background-image: -o-linear-gradient(blue, white);
background-image: linear-gradient(blue, white);
display: flex;
flex-direction: column;
justify-content: center;
height: 100%;
}
.content{
display: flex;
flex-direction: row;
justify-content: center;
}
.boxes-container {
display: flex;
flex-direction: row;
align-content: center;
margin: auto;
}
.box1 {
background: blue;
box-shadow: 0 60px 80px 0 rgba(0,0,0,0.30);
border-radius: 10px;
width: 400px;
height: 271px;
margin: auto;
transform: translateX(25%);
}
.box2 {
background: #FFFFFF;
box-shadow: 0 60px 80px 0 rgba(0,0,0,0.30);
border-radius: 10px;
width: 740px;
height: 586px;
margin: auto;
/*transform: translateX(-30%);*/
transform: translateX(-25%);
z-index: -1;
}
<body>
<div class="content">
<div class="boxes-container">
<div class="box1"></div>
<div class="box2"></div>
</div>
</div>
</body>
关于html - 将两个重叠的盒子水平和垂直居中放置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42548769/