How to create an overlay on div without defining it in HTML

advertisements

I have a web application in which a user creates a complicated fact sheet by entering data into a form. There is a preview of what the final fact sheet will look like, contained in its <div class="preview">. I would like to overlay this preview with something, maybe a transparent diagonal grey text saying "preview". Basically, I want to end up with something like a tiled background, but displayed in front of the element instead of behind it.

I found several solutions for overlays on the Internet, but they assume that I have two separate elements defined in the markup and want to position one on top of the other. But it intuitively feels "cleaner" to me to not have to define the overlay in the markup of the page. So I would prefer a solution which is done purely in the CSS.

The contents of the overlay will be a very simple image, or maybe a transformed text consisting of 1-2 words, or possibly just a transparent color (I haven't decided yet). It will be something which can be easily defined and maintained in a css pseudoclass, if needed.

I am doing a responsive design, so I can't use absolute positioning, and I don't know the size of the area I want to overlay.


Use a pseudo-element, absolute positioning, and CSS3 background sizing:

.preview {
    position:relative;
}
.preview:after {
    content:'';
    background:url(https://mpmath.googlecode.com/svn/trunk/doc/build/_static/preview.png) 50% / contain no-repeat;
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
}

Example fiddle.