问题描述
我正在为CMS构建html / javascript主题设计器。元素被绝对地定位并且可以经由鼠标移动/调整大小,和/或包含可编辑文本,其高度可以由行数确定。但是我遇到了一个问题,其中父元素的高度不扩展,以包括其绝对定位的孩子。
I'm building an html/javascript theme designer for a CMS. Elements are positioned absolutely and can be moved/resized via the mouse, and/or contain editable text whose height may be determined by the number of lines. However I'm running into the problem where a parent element's height does not expand to include its absolutely positioned children.
最小代码(也在):
<style>
div.layer { position: absolute }
div.layer1 { width: 400px; border: 1px solid #ccc }
div.layer2 { top: 15px; left: 100px; width: 100px; border: 1px solid blue }
</style>
<div class="layer layer1">container should expand to the bottom of the child.
<div class="layer layer2" contentEditable>Child with<br/>editable text.</div>
</div>
一个纯CSS解决方案是理想的,我不担心旧的浏览器。但我通常寻找任何方式,以防止需要JavaScript运行在每个页面使用创建的主题来设置其高度(因为具有相同主题的网页可能有不同的文字量)。
A CSS-only solution is ideal and I'm not concerned about older browsers. But I'm mostly looking for any way to prevent the need for javascript to run on every page using a created theme to set their height (since pages with the same theme may have different amounts of text).
已经有一些类似的问题,但他们接受的答案(例如不使用绝对定位)将不能在我的情况下工作。除非有一种方法可以有多层可拖动/可调整大小的元素,而没有位置:绝对。
There are already a few similar questions but their accepted answers (e.g. don't use absolute positioning) won't work in my case. Unless there is a way to have multiple layers of draggable/resizable elements without them being position: absolute.
推荐答案
-css解决方案!总结:
I found a pure-css solution! In summary:
- 将子元素设置为position:relative而不是绝对。
- margin-right成为它们的负宽度,给它们零有效宽度,并使它们浮动:left使它们都保持在同一行上。
- 然后我们可以设置它们的左边和页边空白属性,以将它们绝对定位在他们的父母之内。请注意,margin-top是必需的,而不是top,因为top不会向下按下父元素的底部。
或代码如下:
<style>
div.layer { position: relative; float: left; }
div.layer1 { width: 400px; border: 1px solid black }
div.layer2 { margin-top: 20px; left: 100px; width: 100px; margin-right: -100px; border: 1px solid blue }
div.layer3 { margin-top: 30px; left: 170px; width: 100px; margin-right: -100px; border: 1px solid red }
div.layer4 { margin-top: 30px; left: 20px; width: 60px; margin-right: -60px; border: 1px solid green }
</style>
<div class="layer layer1" style="position: relative; display: block; width: 400px; border: 1px solid black;">
Container
<div class="layer layer2" contentEditable>Edit me</div>
<div class="layer layer3">
<div class="layer layer4" contentEditable>Edit me</div>
</div>
</div>
这篇关于扩展高度以包括绝对定位的孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!