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
148 views
in Technique[技术] by (71.8m points)

html - Text not over Image on View change

I was looking for a solution where I have text on top of an image.

I found solutions similar to this:

                        <div>
                            <div class="centered" style="position:absolute; top:50%; left:50%; transform:translate(-50%, -50%);">
                                No Events found
                            </div>
                            <img src="https://www.steelmint.com/nw/public/images/events-01.svg" alt="Snow" style="width:100%;
position:relative; text-align: center; opacity:0.4;">
                        </div>

Now I realized due to the position-style my text will be displaced if I for example

  • Zoom in/out
  • Change Window Height/Width
  • Switch to Smartphone-View

How is this usually solved so my text stays over my image?

My idea was to just create an image where the text is part of the image and then bind that image to my <img>- Tag. Is this a common way to do?


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

1 Reply

0 votes
by (71.8m points)

Simply use the class on the wrapping div and give it a position: relative; like in the sample below. Then let the div with the text span the entire parent div by using position: absolute; in combination with top, bottom, left and right: 0;. For adding a opacity effect, use rgba as background color instead. It will not cause the same issues as opacity which is rendered last. Use a positive z-index to span the text above the image layer wise.

.text-image-wrapper {
  width: 100%;
  position: relative;
  object-fit: contain;
}

.text-image-wrapper div {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  text-align: center;
  background-color: rgba(255, 255, 255, 0.5);
  z-index: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.text-image-wrapper img {
  width: 100%;
}
<div class="text-image-wrapper">
  <div>Some Exampel Text</div>
  <img src="https://www.tacoshy.de/Images/Yoshi/IMAG0735.jpg">
</div>

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

...