Html 如何在图像上创建响应式文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17415994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create responsive text on top of an image?
提问by Herp
I'm really not sure how to pose this question any other way, but I'm trying to load text on top of an image - which appears to be a tricky task in itself, but I've got it going using thistutorial. Unfortunately, the tutorial is slightly out of date and I can't figure out a way to dynamically change both the font size and the span size for mobile and still maintain the text in the correct place on top of the image.
我真的不确定如何以其他方式提出这个问题,但我正在尝试在图像顶部加载文本 - 这本身似乎是一项棘手的任务,但我已经使用本教程进行了操作。不幸的是,本教程有点过时,我无法找到一种方法来动态更改移动设备的字体大小和跨度大小,并且仍然将文本保留在图像顶部的正确位置。
When the window is resized the text and the box doesn't resize properly (it overflows outside of the image).
当窗口被调整大小时,文本框没有正确调整大小(它溢出图像之外)。
I've tried percentage sizing as well as other techniques with little luck. The CSS I'm using to display the text over the image with a background can be seen below.
我尝试过百分比调整以及其他技术,但运气不佳。我用来在带有背景的图像上显示文本的 CSS 如下所示。
What's the best practice for overlaying text on an image and how would one go about making it responsive? This is what I'm trying to use for desktop browsers right now:
在图像上叠加文本的最佳做法是什么,如何使其具有响应性?这就是我现在尝试用于桌面浏览器的内容:
.herotext span {
position: absolute;
top: 80%;
font-family: 'museo_slab500';
font-size: 150%;
color: #fff;
padding-left: 20px;
width: 40%;
line-height: 35px;
background: rgb(0, 0, 0);
background: rgba(0, 0, 0, 0.7);
}
Does anyone have some advice on how to handle this properly these days? The article I mention above is from 2009 and I suspect it's not the best way to overlay text.
这些天有没有人对如何正确处理这个问题有一些建议?我上面提到的文章是 2009 年的,我怀疑这不是覆盖文本的最佳方式。
回答by Rob Kovacs
Here are the changes I would make:
以下是我要做的更改:
- Position the
span
usingbottom
rather thantop
, so you always have a specific margin between the span and the bottom of the image. - Use a percentage-based
line-height
so that it will change proportionally to thefont-size
- Add some padding to the right of the span, so the text doesn't bump right up on the edge of the span
- 定位
span
usingbottom
而不是top
,因此您始终在图像的跨度和底部之间有特定的边距。 - 使用基于百分比的,
line-height
以便它会按比例变化font-size
- 在跨度的右侧添加一些填充,这样文本就不会在跨度的边缘向上碰撞
Updated CSS:
更新的 CSS:
.herotext span {
position: absolute;
bottom: 20px;
font-family: 'museo_slab500';
font-size: 150%;
color: #fff;
padding: 0 20px;
width: 40%;
line-height: 150%;
background: rgb(0, 0, 0);
background: rgba(0, 0, 0, 0.7);
}