将容器的宽度减小到子元素的宽度,当使用 “left:0” 和 “right:0” 时?

huangapple go评论60阅读模式
英文:

How to reduce width of container to children width when "left:0" and "right:0" are used?

问题

目前,容器被拉伸到max-width,即520px。我注意到这是因为我应用了left:0right:0时发生的。我之所以使用这些属性,是因为我想要将元素(粉色容器)底部居中。

子内容的宽度,包括填充,是206px,但由于min-width240px,我希望粉色容器的宽度为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 -->

&lt;div class=&quot;parentContainer&quot;&gt;
  &lt;div class=&quot;childContainer&quot;&gt;
    &lt;div class=&quot;contentContainer&quot;&gt;
      &lt;h4&gt;Hellow World!&lt;/h4&gt;
      &lt;button&gt;Click Me&lt;/button&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;

<!-- 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;
}

huangapple
  • 本文由 发表于 2023年5月7日 06:49:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76191515.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定