英文:
How to reduce width of container to children width when "left:0" and "right:0" are used?
问题
目前,容器被拉伸到max-width
,即520px
。我注意到这是因为我应用了left:0
和right:0
时发生的。我之所以使用这些属性,是因为我想要将元素(粉色容器)底部居中。
子内容的宽度,包括填充,是206px
,但由于min-width
为240px
,我希望粉色容器的宽度为240px
,但粉色容器仍然为520px
。它不会随着子内容缩小,只会保持在max-width
。
如何调整使粉色容器的宽度根据子内容的宽度进行调整?因此,如果子内容为300px
,我希望粉色容器的宽度为300px
。
.parentContainer {
/* Your CSS styles here */
}
.childContainer {
/* Your CSS styles here */
}
.contentContainer {
/* Your CSS styles here */
}
<div class="parentContainer">
<div class="childContainer">
<div class="contentContainer">
<h4>Hello World!</h4>
<button>Click Me</button>
</div>
</div>
</div>
英文:
Currently, the container is stretched out to max-width
, which is 520px
. I notice this happens when I applied left:0
and right:0
. Reason I used those properties is I would like to bottom center the element(pink container).
The width of child content including padding is 206px
, but since min-width
is 240px
, I would like the width of the pink container to be 240px
wide, but pink container is still at 520px
. It does not shrink with child content, it just stays at max-width
.
How can I make adjustment so that width of pink container adjust according to width of child content? So if child content is 300px
, I would like pink container to be 300px
wide.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.parentContainer {
position: fixed;
left: 0;
right: 0;
margin: 0 auto;
max-width: 520px;
min-width: 240px;
background-color: pink;
bottom: 20px;
}
.childContainer {
display: flex;
flex-direction: column;
align-items: center;
}
.contentContainer {
display: flex;
padding: 20px;
}
<!-- language: lang-html -->
<div class="parentContainer">
<div class="childContainer">
<div class="contentContainer">
<h4>Hellow World!</h4>
<button>Click Me</button>
</div>
</div>
</div>
<!-- end snippet -->
答案1
得分: 1
为了根据子元素宽度调整父元素宽度,您可以对父元素使用 width: fit-content
。
尝试以下代码:
.parentContainer {
position: fixed;
left: 0;
right: 0;
margin: 0 auto;
width: fit-content;
min-width: 240px;
background-color: pink;
bottom: 20px;
}
英文:
In order to adjust the parent width according to the child width, you can use width: fit-content
for the parent.
Try this code out:
.parentContainer {
position: fixed;
left: 0;
right: 0;
margin: 0 auto;
width: fit-content;
min-width: 240px;
background-color: pink;
bottom: 20px;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论