Lightbox with transition

1.2k views Asked by At

I wanted to do a smooth transition of a fullscreen lightbox, my actual code is

<a href="#_" class="lightbox" id="img1">
<img src="images/photo.jpg">
</a>

And my style:

.lightbox {
    display: none;
    position: fixed;
    z-index: 999;
    width: 100%;
    height: 100%;
    text-align: center;
    top: 0;
    left: 0;
    background: rgba(0,0,0,0.8);
}
.lightbox img {
    max-width: 90%;
    max-height: 80%;
    margin-top: 2%;
}
.lightbox:target {
    outline: none;
    display: block;
    transition:all 1s;
}

It's really simple, but transition:all seems to don't work with display block/none... Any idea?

3

There are 3 answers

0
Andrei Surdu On BEST ANSWER

display block/none does not allow any transition to run.

You must use visibility and opacity(for cross browser support).

So your code would look like this:

.lightbox {
    display: block;
    visibility: hidden;
    opacity: 0;
    position: fixed;
    z-index: 999;
    width: 100%;
    height: 100%;
    text-align: center;
    top: 0;
    left: 0;
    background: rgba(0,0,0,0.8);
    transition:all 1s;
}
.lightbox img {
    max-width: 90%;
    max-height: 80%;
    margin-top: 2%;
}
.lightbox:target {
    outline: none;
    visibility: visible;
    opacity: 1;
}
1
Piper McCorkle On

If I recall correctly, transition doesn't work with display. It's not time to give up hope, however! There's opacity! Use opacity: 0 and opacity: 1 in combination with display: none and display: block. Also, your transition is on the .lightbox:target, not the .lightbox. When it's on .lightbox:target, it's too late to start the transition.

Corrected CSS:

.lightbox {
    display: none;
    opacity: 1;
    position: fixed;
    z-index: 999;
    width: 100%;
    height: 100%;
    text-align: center;
    top: 0;
    left: 0;
    background: rgba(0,0,0,0.8);
    transition: opacity 1s;
}
.lightbox img {
    max-width: 90%;
    max-height: 80%;
    margin-top: 2%;
}
.lightbox:target {
    outline: none;
    display: block;
    opacity: 1;
}
0
Yaron U. On

you can't transition display since it has no interim values, it is either displayed or hidden (of course there are many different ways of display) It can't be 25% displayed

in order to create fade in transition with css only, you'll need to use the opacity attribute

function toggle(){
  var element = document.getElementById("element");
  if(element.className==""){
    element.className = "out";
  } else {
    element.className = "";
  }
}
#element{
  transition: all 1s;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.5);
  opacity: 1; 
}

#element.out{
  opacity:0
}

button{z-index: 2; position: relative}
<div id="element">Element</div>

<br />
<button onclick="toggle()">click to fade in/out</button>