英文:
How to make a container's size fits its `position: absolute;` children's size
问题
我正在尝试使一组 <div>
元素在给定的容器内重叠:
.container {
display: inline-block;
position: relative;
}
.block {
position: absolute;
left: 0;
top: 0;
}
This is a <div class="container">
<div class="block" style="background: rgba(255, 0, 0, 0.3);">wonderful</div>
<div class="block" style="background: rgba(0, 255, 0, 0.3);">cool</div>
<div class="block" style="background: rgba(0, 0, 255, 0.3);">great</div>
</div> test!
这样它们将与文本内联。问题是:容器没有宽度或高度,子元素的位置不正确。
关键是不必显式指定容器的大小,而是让 CSS 自动计算,以使这三个单词与句子内联重叠。
英文:
I'm trying to make a set of divs overlap one another inside a given container:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.container {
display: inline-block;
position: relative;
}
.block {
position: absolute;
left: 0;
top: 0;
}
<!-- language: lang-html -->
This is a <div class="container">
<div class="block" style="background: rgba(255, 0, 0, 0.3);">wonderful</div>
<div class="block" style="background: rgba(0, 255, 0, 0.3);">cool</div>
<div class="block" style="background: rgba(0, 0, 255, 0.3);">great</div>
</div> test!
<!-- end snippet -->
So that they are inline with text. The problem is: the container has no width or height, and the children are not properly positioned.
The trick is not to have to specify explicitly the size of the container but have CSS figure it out automatically so that these three words overlap inline with the sentence.
答案1
得分: 1
以下是翻译好的内容:
解决方法是将 container
设置为 inline-grid
并使用 place-items: start
(这样其子元素只占据最小的空间,网格的宽度将由最长的子元素确定),然后将其所有子元素同时设置为 grid-column
和 grid-row
值为 1
:
.container {
display: inline-grid;
place-items: start;
}
.block {
grid-column: 1;
grid-row: 1;
}
这是一个 <div class="container">
<div class="block" style="background: rgba(255, 0, 0, 0.3);">wonderful</div>
<div class="block" style="background: rgba(0, 255, 0, 0.3);">cool</div>
<div class="block" style="background: rgba(0, 0, 255, 0.3);">great</div>
</div> test!
请注意,这部分内容不需要进行翻译。
英文:
A workaround is to set the container
an inline-grid
with place-items: start
(so its children only take minimum space and the grid width will be determined by its longest child), then set all its children with both grid-column
and grid-row
to 1
:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.container {
display: inline-grid;
place-items: start;
}
.block {
grid-column: 1;
grid-row: 1;
}
<!-- language: lang-html -->
This is a <div class="container">
<div class="block" style="background: rgba(255, 0, 0, 0.3);">wonderful</div>
<div class="block" style="background: rgba(0, 255, 0, 0.3);">cool</div>
<div class="block" style="background: rgba(0, 0, 255, 0.3);">great</div>
</div> test!
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论