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

html - :before pseudo-class doesn't work with images

I have following HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>:before pseudo-class and images</title>
    <style type="text/css" media="screen">
        img {
            display: block;
            width: 640pt;
        }
        img:before {
            content: "Test";
        }
    </style>
</head>
<body>
    <img src="http://andreygromov.name/picture/flower/flower4.jpg" alt="Ваза с цветами" />
</body>
</html>

:before will not appear for image, but it does for any div.

Why?


Update: I found this explanation in W3C:

Note. This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.


Update 2:

I forget to mention - i need to visualize "alt" attribute of image with CSS.

img:before {
    display: block;
    content: attr(alt);
    background-color: #333;
    /* etc. */
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Considering the specification you quoted, I guess this is a case where you have to wrap the image in an element and apply :before on that.


EDIT:

Considering, that the alt attribute is for alternative text and basically should confer the same information as the image does, wouldn't that mean you are duplicating the information for the user?

How about putting the information you want to display in the title attribute of the surrounding element and displaying that?

Example:

<style type="text/css" media="screen">
  .image:before {
    content: attr(title);  
  } 
  .image img {
     display: block;
     width: 640pt;
   }
</style>
<div class="image" title="Information here"><img ... ></div>

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

...