js+css Text Blocks Over Image(文字覆盖在图片上)

html图表

<div class="image">

      <img src="images/3754004820_91a5c238a0.jpg" alt="" />
      
      <h2>A Movie in the Park:<br />Kung Fu Panda</h2>

</div>

Putting the image in as a background image of the wrapping div would be easier, but in this scenario I see the images as content, and thus belongs in the HTML. We'll use that wrapping div as a container for absolute positioning.

把图片作为被包围的div的背景图片是简单的,但是现在我把图片作为内容,属于html。

css:

.image { 
   position: relative; 
    100%; /* for IE 6 */
}

h2 { 
   position: absolute; 
   top: 200px; 
   left: 0; 
    100%; 
}

This is going to put our text right up on top of the image nicely, but it doesn't accomplish the transparent black box we want to achieve behind the text. For that, we can't use the h2, because that is a block level element and we need an inline element without an specific width.

为什么用H2不行,因为块级元素会占据这行的整个的页面宽度(如果不指定的话)。这里我们不想指定宽度,

Let's wrap the inside h2 of the in a span:

<h2><span>A Movie in the Park:<br />Kung Fu Panda</span></h2>

The use that span to style the text and background:

h2 span { 
   color: white; 
   font: bold 24px/45px Helvetica, Sans-Serif; 
   letter-spacing: -1px;  
   background: rgb(0, 0, 0); /* fallback color */
   background: rgba(0, 0, 0, 0.7);
   padding: 10px; 
}

Problem

When an inline element breaks, the block breaks immediately after the last character in the line, and begins immediately flush left on the next line. Padding, in this case, does not help us.

当inline元素被打断时,块级元素迅速break,开始在另一行。导致我们上行右边的padding没有设置为10,和下行的左边padding没有设置。

<h2><span>A Movie in the Park:<br />Kung Fu Panda</span></h2> 
即Park:右边padding没有设置 , kungfu左边没有设置padding


To solve this, we'll apply some more spans on either side of the <br />element to simulate that padding.

<h2><span>A Movie in the Park:<span class='spacer'></span><br /><span class='spacer'></span>Kung Fu Panda</span></h2>

Those new spans we'll use to apply padding:

h2 span.spacer {
   padding:0 5px;
}

Fixing Semantics

At this point the design is accomplished, but there there is an awful lot of extra HTML elements added purely for design reasons. Namely, all those spans. jQuery can jump in and save us here. Simply remove all the spans from the markup, and dynamically apply them like this:

$(function() {
    
    $("h2")
        .wrapInner("<span>")

    $("h2 br")
        .before("<span class='spacer'>")
        .after("<span class='spacer'>");

});

via:http://css-tricks.com/text-blocks-over-image/



原文地址:https://www.cnblogs.com/youxin/p/2742065.html