Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create overlay over div without defining it in HTML

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.

like image 681
Rumi P. Avatar asked Dec 13 '25 09:12

Rumi P.


2 Answers

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.

like image 77
Niels Keurentjes Avatar answered Dec 15 '25 23:12

Niels Keurentjes


Beaten to it, but you could add a class to your html, and add a psuedo element to the body, full width, full height.

.overlay body:before{
  content:'Preview mode';
  color:#fff;
  background:rgba(0,0,0,0.8);
  position:fixed;
  top:0%;
  bottom:0%;
  left:0%;
  right:0%;
  width:100%;
  height:100%;
  z-index:1;
}

Example in codepen: http://codepen.io/EightArmsHQ/pen/ByLXao

This way, the pseudo element is at the top / bottom the body, not inside your .preview div, which makes it easier to work with (to fill the full screen – assuming your preview div is only going to fill a part of the screen).

Further example to show clean markup (zero html) http://codepen.io/EightArmsHQ/pen/JoRgja

like image 42
Djave Avatar answered Dec 15 '25 22:12

Djave