我曾多次使用float:右(或左)将图像和嵌入框浮动在容器顶部。现在,我需要浮动一个div到另一个div的右下角与正常的文本包装,你得到的浮动(文本包装上面和左边只有)。
我认为这一定是相对容易的,即使浮动没有底部值,但我还没有能够做到这一点使用一些技术和搜索网络还没有出现任何其他使用绝对定位,但这并没有给出正确的换行行为。
我原以为这是一种很常见的设计,但显然不是。如果没有人有建议,我将不得不把我的文本分解成单独的盒子,并手动对齐div,但这是相当不稳定的,我不想在每个需要它的页面上都这样做。
通过一些JavaScript,我成功地将一个浮动元素固定在它的容器底部——并且仍然让它在文本中浮动,这对于像shape-outside这样的事情非常有用。
被浮动的元素得到一个margin-top赋值,它等于它的容器,减去它自己的高度。这将保留浮动,将元素推到其容器的底边,并防止文本在元素下面流动。
const resizeObserver = new ResizeObserver(entries => {
if(entries.length == 0) return;
const entry = entries[0];
if(!entry.contentRect) return;
const containerHeight = entry.contentRect.height;
const imgHeight = imgElem.height;
const imgOffset = containerHeight - imgHeight;
imgElem.style.marginTop = imgOffset + 'px';
});
const imgElem = document.querySelector('.image');
resizeObserver.observe(imgElem.parentElement);
工作示例:https://codepen.io/strarsis/pen/QWGXGVy
多亏了ResizeObserver和对JavaScript的广泛支持,这似乎是一个非常可靠的解决方案。
If you're okay with only the bottom-most line of the text going to the side of the block (as opposed to completely around and underneath it, which you can't do without ending the block and starting a new one), it's not impossible to float a block to one of the bottom corners of a parent block. If you put some content in a paragraph tag within a block and want to float a link to the bottom right corner of the block, put the link within the paragraph block and set it to float: right, then put in a div tag with clear: both set just underneath the end of the paragraph tag. The last div is to make sure the parent tag surrounds the floated tags.
<div class="article" style="display: block;">
<h3>title</h3>
<p>
text content
<a href="#" style="display: block;float: right;">Read More</a>
</p>
<div style="clear: both;"></div>
</div>