没有绝对位置的图片文字 [英] Text over image without absolute position

查看:90
本文介绍了没有绝对位置的图片文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我看到一个像这样的例子:

 < img src =image.pngstyle =z-index:-1; /> 
< p style =position:absolute; top:1px; left:1px;> text< / p>

,但是当我尝试居中时,文本将不在中心。

 < div> 
< center>
< img src =image.pngstyle =z-index:-1;/>
< p style =position:绝对; top:1px; left:1px;> text< / p>
< / center>
< / div>

如何在没有绝对位置的情况下为图片创建文字?

解决方案

问题不在于绝对定位,而在于文本居中。段落中的文本将居中,但由于段落与文本具有相同的宽度,所以该文本无效。当你完全定位段落时,它不再从它的父元素中获取宽度。



可以使父元素的宽度与图像的宽度相同,而段落宽度相同作为父级,然后将该文本置于段落内。示例:

HTML:

 < div> 
< img src =http://placekitten.com/300/200>
< p>文字< / p>
< / div>

CSS:

  div {
position:relative;
width:300px;
}
p {
position:absolute;
剩下:0;底部:20px;
宽度:100%;
text-align:center;颜色:#fff;
}

演示: http://jsfiddle.net/crp6V/



注意: position:relative; 在父元素上使其成为段落绝对位置的原点。



如果要同时居中图像和文本,那么您只需将该段落的宽度设为与父段相同: http://jsfiddle.net/crp6V/2/


I am trying to put some text over an image in the middle of a page.

I saw an example like this:

<img src="image.png" style="z-index: -1;" />
<p style="position: absolute; top: 1px; left: 1px;>text</p>

but when i try to center it the text will not be in the center.

<div>
    <center>
         <img src="image.png" style="z-index: -1;" />
         <p style="position: absolute; top: 1px; left: 1px;>text</p>
    </center>
</div>

How can i create a text over image without absolute possition?

解决方案

The problem is not the absolute positioning, it's how you center the text. The text in the paragraph will be centered, but that has no effect as the paragraph has the same width as the text. When you make the paragraph absolutely positioned it no longer gets its width from its parent.

You can make the parent the same width as the image, and the paragraph the same width as the parent, and then center the text inside the paragraph. Example:

HTML:

<div>
    <img src="http://placekitten.com/300/200">
    <p>text</p>
</div>

CSS:

div {
  position: relative;
  width: 300px;
}
p {
  position: absolute;
  left: 0; bottom: 20px;
  width: 100%;
  text-align: center; color: #fff;
}

Demo: http://jsfiddle.net/crp6V/

Note: The position: relative; on the parent element makes it the origin for the absolute position of the paragraph.

If you want to center both the image and the text, then you would just make the paragraph the same width as the parent: http://jsfiddle.net/crp6V/2/

这篇关于没有绝对位置的图片文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆