Flexbox horiz/vert 居中超出 <img>
Flexbox horiz/vert centering goes outside of <img>
尝试将 Hello world
horizontally/vertically 置于 .test
的中心,而 .test
延伸至 .test img
的大小。我做错了什么?
.test {
display: flex;
align-items: center;
justify-content: center;
border: 5px solid blue;
}
.test img {
width: 100%;
display: block;
}
.test .test2 {
max-width: 50%;
}
<div class="test">
<img src="http://lorempixel.com/400/400">
<div class="test2">
<p>Hello world</p>
</div>
</div>
由于您将 .test
设为 flexbox,因此其中的 <img>
和 .test2
将以 flex 子元素的方式表现类似,这意味着 <img>
和.test2
会并排出现。
一个解决方案是使 .test2
成为 flexbox 而不是 .test
并让 .test2
绝对定位在 .test
.
之上
.test {
position: relative;
border: 5px solid blue;
}
.test img {
display: block;
width: 100%;
}
.test .test2 {
display: flex;
align-items: center;
justify-content: center;
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
}
<div class="test">
<img src="http://lorempixel.com/400/400" />
<div class="test2">
<p>Hello world</p>
</div>
</div>
尝试将 Hello world
horizontally/vertically 置于 .test
的中心,而 .test
延伸至 .test img
的大小。我做错了什么?
.test {
display: flex;
align-items: center;
justify-content: center;
border: 5px solid blue;
}
.test img {
width: 100%;
display: block;
}
.test .test2 {
max-width: 50%;
}
<div class="test">
<img src="http://lorempixel.com/400/400">
<div class="test2">
<p>Hello world</p>
</div>
</div>
由于您将 .test
设为 flexbox,因此其中的 <img>
和 .test2
将以 flex 子元素的方式表现类似,这意味着 <img>
和.test2
会并排出现。
一个解决方案是使 .test2
成为 flexbox 而不是 .test
并让 .test2
绝对定位在 .test
.
.test {
position: relative;
border: 5px solid blue;
}
.test img {
display: block;
width: 100%;
}
.test .test2 {
display: flex;
align-items: center;
justify-content: center;
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
}
<div class="test">
<img src="http://lorempixel.com/400/400" />
<div class="test2">
<p>Hello world</p>
</div>
</div>