如何在柔光盒中居中放置图像?我尝试使用辩解内容和align-items居中,但这没有用。
在下面的代码中,我将我设置为绿色框。我想将绿色框放在红色框的中央。有帮助吗?
.body{
display: flex;
flex: 1;
width: 250px;
height: 250px;
background-color: blue;
padding: 10px;
}
.innerDiv1{
flex: 1;
background-color:red;
}
.innerDiv2{
flex: 1;
background-color: yellow;
}
.innerDiv3{
flex: 1;
width: 50px;
height: 50px;
background-color: green;
align-items: center; /*does not work*/
justify-content: flex-end; /*does not work*/
}
<div class = "body">
<div class = "innerDiv1">
<div class = "innerDiv3">
</div>
</div>
<div class = "innerDiv2">
</div>
</div>
答案 0 :(得分:4)
您需要将window.
,display: flex
和align-items: center
添加到绿色框(justify-content: center
)的父级,而不是绿色框(.innerDiv1
)本身:
.innerDiv3
.body {
display: flex;
width: 250px;
height: 250px;
background-color: blue;
padding: 10px;
}
.innerDiv1 {
flex: 1;
background-color:red;
/* HERE ? */
display: flex;
align-items: center;
justify-content: center;
}
.innerDiv2 {
flex: 1;
background-color: yellow;
}
.innerDiv3 {
width: 50px;
height: 50px;
background-color: green;
}
或者,您可以将<div class="body">
<div class="innerDiv1">
<div class="innerDiv3">
</div>
</div>
<div class="innerDiv2"></div>
</div>
添加到父项(display: flex
)并将.innerDiv1
+ align-self: center
添加到绿色框(margin: 0 auto
):
.innerDiv3
.body {
display: flex;
width: 250px;
height: 250px;
background-color: blue;
padding: 10px;
}
.innerDiv1 {
flex: 1;
background-color:red;
/* AND HERE ? */
display: flex;
}
.innerDiv2 {
flex: 1;
background-color: yellow;
}
.innerDiv3 {
width: 50px;
height: 50px;
background-color: green;
/* AND HERE ? */
align-self: center;
margin: 0 auto;
}
答案 1 :(得分:3)
您必须将display:flex
应用于父级,并且还必须在父级上设置justify-content
和align-items
您可以在此处查看有关对齐的更多详细信息:Align Items in Flexbox
.body{
display: flex;
flex: 1;
width: 250px;
height: 250px;
background-color: blue;
padding: 10px;
}
.innerDiv1{
flex: 1;
background-color:red;
display: flex;
align-items: center;
justify-content: center;
}
.innerDiv2{
flex: 1;
background-color: yellow;
}
.innerDiv3{
width: 50px;
height: 50px;
background-color: green;
}
<div class = "body">
<div class = "innerDiv1">
<div class = "innerDiv3">
</div>
</div>
<div class = "innerDiv2">
</div>
</div>
答案 2 :(得分:0)
您应该将绿色div
与红色div
对齐,例如,要使子元素位于其父元素的中心,您应该对齐父div的内容而不是子div的内容(在您的大小写),方法是将align-items: center;
和justify-content: center;
添加到红色的div
中:
.body{
display: flex;
flex: 1;
width: 250px;
height: 250px;
background-color: blue;
padding: 10px;
}
.innerDiv1{
display: flex;
flex: 1;
align-items: center;
justify-content: center;
background-color: red;
}
.innerDiv2{
flex: 1;
background-color: yellow;
}
.innerDiv3{
width: 50px;
height: 50px;
background-color: green;
}
<div class = "body">
<div class = "innerDiv1">
<div class = "innerDiv3">
</div>
</div>
<div class = "innerDiv2">
</div>
</div>