在flexbox中,我有一个带有2列的部分居中,但是由于某种原因,容器并没有将其水平包裹,而是充满了整个页面。
我该怎么做才能使该部分环绕文本(预期填充为1rem)?
body {
background-color: #444;
color: white;
}
section {
border-style: solid;
border-image: linear-gradient(to top right, goldenrod 0%, transparent 25%, transparent 75%, goldenrod 100%) 2;
display: flex;
padding: 1rem;
justify-content: center;
align-items: center;
width: auto;
}
section>div {
display: flex;
flex-direction: column;
}
section>div:first-child {
border-right: 2px solid goldenrod;
padding-right: 1rem;
align-items: flex-end;
}
section>div:not(:first-child) {
padding-left: 1rem;
}
<section>
<div>
<p>Line First</p>
<p>Line Second</p>
</div>
<div>
<p>Line First</p>
<p>Line Second</p>
</div>
</section>
JSFiddle: https://jsfiddle.net/mjp1qozs/3/
答案 0 :(得分:0)
答案是将display
更改为inline-flex
。谢谢Temani Afif!
答案 1 :(得分:0)
使用display: inline-flex
(如上面的注释中所建议),您可以实现所需的收缩包装行为,但同时也失去了水平居中的功能。因此,您解决了一个问题,却创建了另一个问题。
相反,只需将父容器设置为带有justify-content: center
的flex容器即可。只需两行代码即可解决这两个问题。
body {
display: flex; /* new */
justify-content: center; /* new */
background-color: #444;
color: white;
}
section {
border-style: solid;
border-image: linear-gradient(to top right, goldenrod 0%, transparent 25%, transparent 75%, goldenrod 100%) 2;
display: flex;
padding: 1rem;
justify-content: center;
align-items: center;
width: auto;
}
section>div {
display: flex;
flex-direction: column;
}
section>div:first-child {
border-right: 2px solid goldenrod;
padding-right: 1rem;
align-items: flex-end;
}
section>div:not(:first-child) {
padding-left: 1rem;
}
<section>
<div>
<p>Line First</p>
<p>Line Second</p>
</div>
<div>
<p>Line First</p>
<p>Line Second</p>
</div>
</section>