Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

css - How to create responsive text on top of an image?

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 this tutorial. 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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here are the changes I would make:

  • Position the span using bottom rather than top, 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 the font-size
  • Add some padding to the right of the span, so the text doesn't bump right up on the edge of the span

Updated 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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...