Kiran
Kiran

Reputation: 916

CSS color change in basic HTML document

Consider the following code:

<html>

<head>
  <style>
    body {
      background-color: #CCC;
    }

    .con {
      background-color: #FFF;
      width: 80%;
      margin: 0 auto;
    }
  </style>
</head>

<body>
  <div class="con">
    [SITE CONTENT]
  </div>
</body>

</html>

What I am trying to achieve is to have the content background in white color which takes 80% of the screen width and will be in center.

Body background (10% right and 10% left) will be of gray color. (80% of the center will be occupied by the content div with white background).

It is working fine. But most of the times when the page loads, (mostly when network is slow), initially the content also will appear in gray background and then it changes to white.

What is the best way to avoid this transition effect?

I am now thinking of the following options:

a. Change color of body at the end using js

b. Initially in , background color of body also be white and then at the end of document, override css and make it gray.

But I am sure there is a better solution. Please help.

Upvotes: 3

Views: 112

Answers (2)

R_Ice
R_Ice

Reputation: 684

What about this? Credits to A.M.K

body {
  -moz-animation: fadein 4s;
  /* Firefox */
  -webkit-animation: fadein 4s;
  /* Safari and Chrome */
  -o-animation: fadein 4s;
  /* Opera */
  background-color: #ccc;
}

@keyframes fadein {
  from {
    background-color: #fff;
  }
  to {
    background-color: #ccc;
    ;
  }
}

@-moz-keyframes fadein {
  /* Firefox */
  from {
    background-color: #fff;
  }
  to {
    background-color: #ccc;
    ;
  }
}

@-webkit-keyframes fadein {
  /* Safari and Chrome */
  from {
    background-color: #fff;
  }
  to {
    background-color: #ccc;
    ;
  }
}

@-o-keyframes fadein {
  /* Opera */
  from {
    background-color: #fff;
  }
  to {
    background-color: #ccc;
    ;
  }
}

.con {
  background-color: #FFF;
  width: 80%;
  margin: 0 auto;
}

Upvotes: 1

You might try something like this without using jQuery:

Set your html in display: none;. Then when your page is loaded changes to display: block; to show the html content.

setTimeout(function() {
  var html = document.querySelector("html");
  html.setAttribute("style", "display: block");
}, 1000);
html {
  display: none;
}
body {
  background-color: #CCC;
}
.con {
  background-color: #FFF;
  width: 80%;
  margin: 0 auto;
}
<body>
  <div class="con">[SITE CONTENT]</div>
</body>

Another way is using jQuery library:

$(function() // When the DOM is ready.
{
    $("html").css({
      "display": "block"
    });
});
html {
  display: none;
}
body {
  background-color: #CCC;
}
.con {
  background-color: #FFF;
  width: 80%;
  margin: 0 auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<body>
  <div class="con">[SITE CONTENT]</div>
</body>

I hope this helps you.

Upvotes: 1

Related Questions