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

html - Position text over image

I have this image:

enter image description here

But i want to place text in the middle like this:

This is how i wanted.

How can I achieve this?

I would like to do this in html, so I would use a <div> or a <span>

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Using Pseudo Elements

The above could be created using the ::before and ::after pseudoelements of the containing element. For instnace, suppose we started with this:

<h1>Keep Calm and Stack Overflow</h1>

We could target the two pseudo elements, set their dimensions and background images, and get the same effect you are seeking above.

h1::before, h1::after {
    content: ""; display: block; height: 3em;
    background: url('ribbon.png') center center;
}

The above is a mere example of what you may write. For a fuller demo, please see this fiddle.

enter image description here

Using a Background Image (Original 2010 Answer)

Create a div that is the dimensions of your image. Then place your text inside. Use margins/padding on your text to get it vertically-centered, and set text-align to "center" for its CSS.

.imgBox  { 
    width: 300px; height: 100px; 
    background-image: url('bg.jpg');
}
.imgText { 
    text-align: center; 
    margin: 0; padding: 25px 0 0 0;
}
<div class="imgBox">
  <p class="imgText">Hello World</p>
</div>

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

...