如何将文本与使用 object-fit 自动缩放的图像对齐:包含
How to align text to image that is auto scaled with object-fit: contain
我有一个占屏幕大约 75% 的视口,我使用 object-fit: contain
css 将不同宽高比的单张图像放入其中。在图像上方,我有文件名和类型的文本标签。我想让它们对齐以从图像的最左边缘开始并在最右边缘结束。我之前可以通过将它们与 <img>
标记对齐来轻松做到这一点。
使用 object-fit: contain
的一个副作用是 <img>
元素比可视图片大,因此当我尝试将文本与 <img>
对齐时,文字漂浮在图像之外。
当 img
标签扩展到适合整个视口但实际图片在 img
标签内使用 [=10= 自动缩放时,如何将文本与可视图像对齐]?
解决方案在很大程度上取决于标记、固定宽度 and/or 高度等。
假设您事先不知道他们的width/height,您将需要一个脚本,如下例所示。
已更新:我添加了 opacity
以便同时显示图像和文本。
如果你知道,你还需要搞出一堆CSS动画规则,包括他们的比例和动画设置,让它看起来好看,这是可以做到的,虽然这需要一些工作。 this answer 的末尾是如何根据 fit-content
计算大小的相同方式设置元素大小的示例。
document.querySelector('img').addEventListener('load', function(e) {
document.querySelector('.image-text').style.cssText = 'width: ' + e.target.width +'px; opacity: 1;';
})
.image-wrap {
position: relative;
height: 200px;
overflow: hidden;
border: 1px dashed gray;
margin-bottom: 10px;
}
.image-wrap img { /* fit-content replacement */
position: relative;
max-height: 100%;
max-width: 100%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
div.image-text {
opacity: 0;
margin: 0 auto;
}
<div class="image-text">Some text we want to size and break at the same width as the image</div>
<div class="image-wrap">
<img src="http://placehold.it/500x400" alt="some image here" />
</div>
这是另一个 post 关于获取自然尺寸和缩放尺寸的图像:
我有一个占屏幕大约 75% 的视口,我使用 object-fit: contain
css 将不同宽高比的单张图像放入其中。在图像上方,我有文件名和类型的文本标签。我想让它们对齐以从图像的最左边缘开始并在最右边缘结束。我之前可以通过将它们与 <img>
标记对齐来轻松做到这一点。
使用 object-fit: contain
的一个副作用是 <img>
元素比可视图片大,因此当我尝试将文本与 <img>
对齐时,文字漂浮在图像之外。
当 img
标签扩展到适合整个视口但实际图片在 img
标签内使用 [=10= 自动缩放时,如何将文本与可视图像对齐]?
解决方案在很大程度上取决于标记、固定宽度 and/or 高度等。
假设您事先不知道他们的width/height,您将需要一个脚本,如下例所示。
已更新:我添加了 opacity
以便同时显示图像和文本。
如果你知道,你还需要搞出一堆CSS动画规则,包括他们的比例和动画设置,让它看起来好看,这是可以做到的,虽然这需要一些工作。 this answer 的末尾是如何根据 fit-content
计算大小的相同方式设置元素大小的示例。
document.querySelector('img').addEventListener('load', function(e) {
document.querySelector('.image-text').style.cssText = 'width: ' + e.target.width +'px; opacity: 1;';
})
.image-wrap {
position: relative;
height: 200px;
overflow: hidden;
border: 1px dashed gray;
margin-bottom: 10px;
}
.image-wrap img { /* fit-content replacement */
position: relative;
max-height: 100%;
max-width: 100%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
div.image-text {
opacity: 0;
margin: 0 auto;
}
<div class="image-text">Some text we want to size and break at the same width as the image</div>
<div class="image-wrap">
<img src="http://placehold.it/500x400" alt="some image here" />
</div>
这是另一个 post 关于获取自然尺寸和缩放尺寸的图像: