How to create a toast notification in few lines of code

I recently was about to ship a new system when I remember that many months ago I decided to create an error message at the top of the application which was having few constraints. My initial thought was that this error banner would be there only for an unhandled exception which wouldn’t be the central error area. That still stands. For example, forms were getting their validation directly at the input level. However, the reality is that an Ajax error can happen and one of my forms could be out of range of the header. The result is that a user might not see the mistake at all which would be bewildered about why is the data not being processed.

With very little time, I had to refactor the user interface. I first had the idea of using an on-the-shelf solution. But, after few minutes I thought that since it is an exceptional case, I can probably tinker simple CSS solution that would fit perfectly in my React application. Within one hour, I had the whole solution written and tested on many screen resolutions. This article has a simplified equivalence of what I created without being strongly associated to React or TypeScript.

The first piece is that when an error occurs to create the HTML structure that will hold the message.

<div class="toast">
  <p>Your message</p>
</div>

The idea is to have a container. The inside can be a simple message or an icon with a message. In my case, I had an icon, a header, a text and a dismiss button that can call a Redux action to remove the message from the Redux’s store. As I said, this is all optional and is not required for the idea to work. The next step is to shape the end result of the error panel that would remain at the bottom of the browser windows regardless if the user is scrolling or has scrolled.

.toast{
  position:fixed;
  bottom:10px;
  left: 10px;
  width:250px;
  border-radius: 4px;
  box-shadow: #310808 1px 1px 5px;
  background-color: rgba(177, 7, 15, 0.78);
  padding:10px;
  color: #f5bfbf;
}

The CSS is pretty basic and leverages the position “fixed”. On the actual code, I had some media instruction to have the width to span the whole width of the browser if the resolution was low by setting the right value and width to auto.

The second piece is to have the toast appearing gracefully. This can be done with purely CSS. The idea is to set an animation that will be executed once. The start of the animation should be that the container is hidden and out of the screen with the end of the animation to its final position with full opacity. The CSS needs to have 3 more lines.

  opacity:1;
  animation: toast 500ms cubic-bezier(.23,.82,.16,1.46);
  animation-iteration-count: 1;

The animation is called “toast” and iterate once and has a duration of 500ms. The cubic-bezier is set to create a bouncy effect.

@keyframes toast{
  0%{
    opacity:0;
    transform: translateY(200px);
  }

  100%{
    opacity:1;
    transform: translateY(0px);
  }
}

The end result is as planned which pop once when the error is added into the DOM.

Indeed, this solution is not elaborated and mundane to anyone using something more rich in feature. However, the size of this solution is tiny and for an edge case fit perfectly the situation. If you want to see the code in action I created a CodePen.

How to have Chrome Style Inspector to Show Input Placeholder

One habit I have is to set the classes to my HTML elements and then go in Chrome to write all the style. Once I am satisfied, I copy paste everything in the style sheets. Recently, I had to modify the placeholder text to be in a specific color and style — Chrome’s inspector couldn’t bring the style of the pseudo-element ::placeholder.

The reason is that the placeholder is hidden under the “shadow-root”. The element hides in the Element Explorer, you cannot select the element to see or edit its styles. Chrome lets you configure the developer tool to bring the “shadow-root” into the Elements panel.

The first step is to go in the three dots menu and select “Settings”. Under the “Preferences” tab and the selection “Elements”, you need to check the “Show user agent shadow DOM”.

Going back to the elements panel, you will see the shadow dom under the input.

By clicking the “div” inside the “#shadow-root (user-agent)” you can see in the styles panel all the common styles as you would expect.

Visual Studio Code with NPM and TypeScript (Part 8 : SASS & CSS)

Transforming SCSS into CSS is a matter of using less than 5 lines of code. NPM has a package that you can use with Gulp. In less than 5 minutes, you can have SCSS configured to compile all your files into CSS.

The first step is to get the gulp sass package. You need to install the dependency has development since you won’t need it at the browser level.

npm install gulp-sass --save-dev

The next step is to create a step that will take all you scss files, pipe the files into the sass compiler and pipe the output into your output folder, where you will references them from your HTML file to serve the style. Here is the Gulp task.

gulp.task('scss', function() {
  gulp.src('sass/**/*.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('./css/'));
});

You can find all changes for SCSS inside this commit[1] for the project we are building up. You may see some differences in the commit compared to this blog post. For example, instead of relying on string directly inside the task for path, I opted to use a constant. It’s always better to have in a centralized way in case of change or in case that it can be reused in another task.

Another change that you might consider is to add this new created task in the dependency of tasks for the build task or the watcher.

Here is a screenshot of the output where the SCSS generates CSS that modify the HTML.

SCSS:

body{
    font-size:36px;
    span{
        font-size:6px;
    }
}

CSS:

body {
  font-size: 36px; 
}
body span {
    font-size: 6px; 
}

HTML Output:

[1]:https://github.com/MrDesjardins/TypescriptNpmGulp/commit/02410d535a12cb48b167ff45b18970d312776270

CSS Sticky Position

Before going any further, this is supposed by Chrome 56+ and not many browser yet. The actual Chrome stable version is 56, hence it should be used with a good fallback.

Sticky position is a new CSS position that allow to have a sticky element that is not sticky all the time. This is different from fixed which place an HTML element in a place and never move. With position to sticky, you define a threshold where the element will change from relative to “fixed”.

To illustrate, image a list that has a lot of element and once in a while you have title that you want to stick for the section. When scrolling, you want the title to unstick when you reach a new section. Every active section should have its own title fixed at the top. This can be achieved by JavaScript or now with Sticky. Here is a simple example of CSS that is applied to a class name “list-header” which should be used in each of section’s title.

.list-header { 
    position: sticky; 
    top: 5px; 
}

Every time the user scroll down, if the title reach the top by 5px (so not already touching the top but almost) the sticky get away until a new title reach the top. Normally, you want a very small number because otherwise, it will start getting sticky too early. In the example above, you would see a 5px game between the top of the title and the top of the container. A top of 1 or -1 would make more sense because the title would be almost flush to the top of the container.

You can see an example (inspired by Mozilla’s documentation) here : https://codepen.io/mrdesjardins/pen/RpwLMy which will produce this output:

How to cache Html element with Html5 Canvas and LocalStorage

This caching idea is limited to some scenarios where you have defined html zones. For example, if you are working with dynamic charts or having a complex logic to render Html controls or even complex canvas. In all cases, the goal is to show to the user something relevant instead of just a loading spinner for the subsequent calls.

The concept is that once you have loaded the zone the first time, you take a snapshot and store it into the local storage as a visual copy — an image. The idea behind using an image is that you do not have to wait for extra dependencies like JavaScript files, CSS stylesheets or Ajax calls to have something displayed to the user. Meanwhile, the normal flow of your application must continue to have the real html loading with fresh values from the backend. The major advantage of that solution is that you have no slowness because of the network, neither of the server or from complex rendering client side code — you get it directly pre-rendered from the client side cache.

This article will show you how to take a screenshot,in JavaScript, with the library called Html2Canvas, stores it into the local storage and how to do the swap between this fake cached view with the real Html one. First, let’s create an example scenario with two zones. One zone, called box1 will take 3 seconds to load and the box2 will take 5 seconds. The goal is to display the fake cached view when loading the real data, and thus make it appearing to the user as it was already loaded.

This solution is having some caveats. First, if the time between the image and the real html takes too much time, than the user may be confused. Thus, this is a good solution for improving a solution that has good performance on the start. I would say that you can easily use that solution for zones that load without this trick under 3-5 seconds. You can always have a subtle loading visual hint somewhere if it’s longer. Second, if the cached image is very different from the new visual, than it will flicker during the swap of the image to the real html. Third, the local storage is limited in size, between 5 to 10 megs. That mean that you are limited to what you can cache with that solution. Overall, this solution is not a silver bullet and should be used as a blazing fast boost experience to an experience that is reasonable to load. It’s not a solution to apply to a menu for example, because user may interact very fast with it and would hit a wall or should I say an image. It’s good for element in a page that has a high visual interest or with element that has basic interaction like linking to somewhere else because the image can fulfill that contract.

Let’s dive in the code.

<div id="box1" class="box"><i class="fa fa-spinner fa-spin"></i></div>
<div id="box2" class="box"><i class="fa fa-spinner fa-spin"></i></div>
.box{
    width:150px;
    height:150px;
    background-color:lightblue;
    margin:10px;
}

.box i{
    font-size: 3em;
}

This will produce the following html :
2LoadingZonesBoxes

The normal loading experience is done by using JavaScript’s timeout. Both box display a different text, one display also an image.

setTimeout(renderBox1, 3000);
setTimeout(renderBox2, 5000);
function renderBox1()
{
    var $box = $('#box1');
    $box.text('Loaded 1');
    var $icon = $('<i>').addClass('fa fa-hand-peace-o');
    $box.append($icon);
}

function renderBox2()
{
    var $box = $('#box2');
    $box.text('Loaded 2');
}

So far, it takes the amount of time defined to see the spinner being removed and replaced by the real content.

The next step is to have in those render box the code to set the cache with the image of the rendered result. Box 1 will have the text and the image, box 2 just the text. This require to change both render method to call a cache method. Since the experience is so seamless that we will also, for the purpose of this demo, add some text under the boxes once refreshed with real value. So, the visual will be on the first call that we display the spinner, we cache, we display the text under the box. On the second load, we do not display the spinner since this one is replaced by the cached version right away. The texts under the boxes are shown only after the delay with the real value.

function renderBox1()
{
    var $box = $('#box1');
    $box.text('Loaded 1');
    var $icon = $('<i>').addClass('fa fa-hand-peace-o');
    $box.append($icon);
    cache($box);
    $box.after('<p>Not cached data box 1 in place</p>');
}

function renderBox2()
{
    var $box = $('#box2');
    $box.text('Loaded 2');
    cache($box);
    $box.after('<p>Not cached data box 2 in place</p>');
}

We also need to change the loading code to go check in the cache. We try to read the cache, the local storage, and if nothing

var box1Cached = unDataToCanvas(localStorage.getItem('box1'));
var box2Cached = unDataToCanvas(localStorage.getItem('box2'));

if(box1Cached){
     $('#box1').html(box1Cached);
}
setTimeout(renderBox1, 3000);


if(box2Cached){
    $('#box2').html(box2Cached);
}
setTimeout(renderBox2, 5000);

Finally, the load and save in the cache need to be coded. The save will create a canvas and we will store the data into a base64 representation. This is done by calling the method “toDtaUrl()” method.

function cache($elementToCache)
{
    var id = $elementToCache.attr('id');
    html2canvas($elementToCache, {
          onrendered: function(canvas) {
            window.localStorage.setItem(id, canvas.toDataURL());
          }
        });
}

The loading is more tricky. We need to load from the local storage the base64 image, create an image with the source to this base64 and return it.


function unDataToCanvas(data) {
    var img = new Image();
    var canvas = document.createElement('canvas');
    img.onload = function() {
        canvas.width = 150;
        canvas.height = 150;
        canvas.getContext("2d").drawImage(img, 0, 0);
    };
    img.src = data;
    if(data){
    	return img;
    }
    else{
    	return null;
    }
}

The whole code with a working demo is on JsFiddle.net : http://jsfiddle.net/mrdesjardins/31qca6b0/.

How to create a bottom-right fixed button in CSS with expanding hover animation

If you need to have a button with minimal information and when the user hovers this one give more input before executing the action, here is something interesting. The code illustrates a use case that the button is fixed to the browser at the bottom-right of the screen but this kind of button can be used everywhere. The main purpose is to have a rich user experience with pro-active feedback in a minimal way. The initial state of the button is just a single icon.

PlusImage
Expected rendering

For that example, I haven’t use a glyph icon, neither an image, just a single plus character. This could be replaced with what ever you want. The idea is that when the user hover the icon that we have a transition to a bigger button.

Here is the button’s Html. The container is not required and is just there for the purpose of having this button sticky at the bottom-right of the window. The button element is the real button. This one will grows when hovering. It contains two texts: one when collapsed and one when extended.

<div class="right-corder-container">     
	<button class="right-corder-container-button">         
		<span class="short-text">+</span>         
		<span class="long-text">Add Me</span>     
	</button> 
</div>

The css does 90% of the job. The remaining 10% is that we need to have a hover JavaScript to add and remove a class to add the long text visibility. The first CSS style is about fixing the container at the bottom-right of the browser’s window.

.right-corder-container {     
    position:fixed;     
    right:20px;     
    bottom:20px; 
}

The next CSS style is what round up the button into a perfect circle. This is also where we setup the transition effect timing.

.right-corder-container .right-corder-container-button {     
     height: 62px;     
     width: 62px;     
     border:none;    
     background-color:#6FB583;     
     border-radius: 62px;        /*Transform the square into rectangle, sync that value with the width/height*/     
     transition: all 300ms;      /*Animation to close the button (circle)*/     box-shadow:2px 2px 5px rgb(25, 73, 15);     
     cursor:pointer; 
}

The span specify the plus sign to be placed in the middle. We use absolute position to have fined precision about where to place the text. Also, this is easier to ensure that even during the effect that this one remains at the same place.

.right-corder-container .right-corder-container-button span {     
    font-size: 72px;     
    color:white;     
    position: absolute;    
    left: 10px;     
    top: 16px;     
    line-height: 28px; 
}

The hover is where we specify the size of the final stage of the button. We also change the right side to be less round. This way, the button appears to be less than an oval, more to a label.

.right-corder-container .right-corder-container-button:hover {     
    transition: all 400ms cubic-bezier(.62,.1,.5,1);     
    width:200px;     
    border-top-right-radius: 5px;     
    border-bottom-right-radius: 5px; 
}

The next style block is about the long text effect. We want this text to appear slowly. We need to tweak some properties to be sure that the vertical scroll-bar does not get affected.

/*     Long text appears slowly with an animation. That code prepare the animation by hidding the text.     The use of display is not there because it does not work well with CSS3 animation. */ 
.right-corder-container .right-corder-container-button .long-text {     transition: opacity 1000ms; /*Only the text fadein/fadeout is animated*/     
opacity:0;                /*By default we do not display the text, we want the text to fade in*/     
color:white;     
white-space: nowrap;     
font-size: 0;             /*Set to 0 to not have overflow on the right of the browser*/     
width: 0;                 /*Set to 0 to not have overflow on the right of the browser*/     
margin:0;                 /*Set to 0 to not have overflow on the right of the browser*/ }


This is how we show the long text. We need to add a delay in the transition opacity because we do not want to start showing the text too early. Mostly because the container size is animated and not big enough to receive the text yet.

 /*     Animation to have a text that appear progressively. We need to play with a delay     on the width and the font-size to not have the browser have the text appears on the right     side of the browser view port. This has the side-effect of having an horizontal bar. */ 
.right-corder-container .right-corder-container-button .long-text.show-long-text{   
    transition: opacity 700ms,               
    width 1ms linear 270ms,       /*two thirds of the animation on the container width*/               
    font-size 1ms linear 270ms;   /*two thirds of the animation on the container width*/   
    opacity:1;   
    margin-top: 2px;                          /*Center the position vertically*/   
     margin-left: 65px;                        /*Center between the + and the right end side*/   
    font-size: 20px;                          /*Text size, cannot be defined initially without moving the scrollbar*/   
    width: auto;                              /*Required to be set with a delay (see animation) to not have scrollbar. Delay is to wait container to size up*/ 
}


The JavaScript is minimal and you do not have to use JQuery for a simple task as this. However, I had this one already available to here is the code with JQuery.

$(".right-corder-container-button").hover(function() 
{     
$(".long-text").addClass("show-long-text"); }, function () {     $(".long-text").removeClass("show-long-text"); 
});

This code is available in JSFiddle.

Quick Add Html Button with CSS3 and JQuery

This is a small JavaScript and CSS control that allows to have some edition from a textbox in a fashion that this one is only a button to minimize space and once clicked become a more extended version. The goal is to have a way to add information in a quick way without taking too much space. This is perfect for situation where adding information is not the main task. The use case is that a user want to add information which require a text box. The user click the button to open the edition which reveal a text box. The button does not need to stay there because we want to save space so the button transforms into a closing button which cancel the operation if required. When the user starts to type, a save button is added. From there, the user can click the cancel button or hit save. In both case, the text box is rolling back and the user interface come back to the initial state. This design is intended to be minimal. There is not label. This is why we need to use a watermark, also known as placeholder in the text box. Since we want to limit button, the expand button and cancel (collapse) button is the same. To make sure that the user knows what the button is doing we display a tooltip but also we have an animation that transform visually the button to its intend.

To keep it simples, let’s start with a division that will hold all our Html elements.

<div id="container">
</div>

Next, we need to create our three main controls. The first one is the input where the user will write any information that will be saved. The second one is the toggle button that expand or collapse the input box and the third one is the save button that will be displayed only when the user save.

var $controlContainer = $('#container');

var $inputBox = $("<input>")
	.attr('id', 'inline-editor-textbox')
        .attr('type', 'text')
	.attr('value', '')
	.attr('maxlength', 20 )
	.attr('style', 'display:none')
	.attr('placeholder', "This is some watermark")
	.addClass('hide-input-inline')
	;
$inputBox.appendTo($controlContainer);

var $buttonToggle = $("<button>")
	.attr('id', 'toggleButton')
	.attr('title', 'Open')
	.attr('type', 'button');
var $spanIcon = $('<span>')
	.addClass("glyphicon glyphicon-plus");
$spanIcon.appendTo($buttonToggle);
$buttonToggle.appendTo($controlContainer);

var $buttonOk = $("<button>")
	.attr('id', 'okButton')
	.attr('style', 'display:none')
	.attr('title', 'Ok')
	.addClass('hide-ok-button')
	.attr('type', 'button');
var $spanIconOk = $('<span>')
	.addClass("glyphicon glyphicon-save");
$spanIconOk.appendTo($buttonOk);
$buttonOk.appendTo($controlContainer);

The next step is to add events. The toggle will open and close the input. It will also change the icon of the button from a “+” to a “x”. The okay button will save the information and collapse the input if everything is fine. The keyup is there to show the save button if the text box contains text.

$buttonToggle.click({ input: $inputBox, buttonToggle: $buttonToggle, buttonOk: $buttonOk},onToggle);
$buttonOk.click({ input: $inputBox, buttonToggle: $buttonToggle, buttonOk: $buttonOk},onOk);
$inputBox.keyup( { input: $inputBox, buttonOk: $buttonOk }, onKeyUp);

The toggle function has reference to some of our controls. This is a great way to pass reference without having to communicate through JQuery selector. Depending of the state of the toggle, which is the class “hide-input-inline” we make it appears or not. We add a delay because we have CSS3 animation and we want everything to be smooth together.

function onToggle(jqueryEvent) {
	var data = jqueryEvent.data;
	var $input = data.input;
	var $buttonToggle = data.buttonToggle;
	var $buttonOk = data.buttonOk;

	var isHidden = $input.hasClass("hide-input-inline");
	if (isHidden) {
		$input.fadeIn();                            
		$input.removeClass("hide-input-inline");    
		$input.addClass("show-input-inline");       
		$input.val('');                             
		$buttonToggle.addClass("add-to-close");     
		$buttonToggle.attr('title', 'Close');
	}
	else {
		$input.removeClass("show-input-inline");   
		$input.addClass("hide-input-inline")      
			.delay(600)
			.fadeOut();                             
		$buttonToggle.removeClass("add-to-close");  
		$buttonOk.addClass("hide-ok-button");     
		$buttonOk.removeClass("show-ok-button")
			.delay(600)
			.fadeOut();                             
		$buttonToggle.attr('title', 'Open');
	}
}

The key up is to check the length but we could also check for “Enter” to be pressed and invoke the Ok code. The code is adding or removing classes, with a delay to let CSS animation to be executed.

function onKeyUp(jqueryEvent) {
	var data = jqueryEvent.data;
	var $input = data.input;
	var $buttonOk = data.buttonOk;
	if ($input.val().length === 0) {
		$buttonOk.removeClass("show-ok-button");
		$buttonOk.addClass("hide-ok-button")
			.delay(600)
			.fadeOut(); 
		htmlElementWithIconState($buttonOk, true);
	} else {
		$buttonOk.fadeIn();
		$buttonOk.addClass("show-ok-button");
		$buttonOk.removeClass("hide-ok-button");
		htmlElementWithIconState($buttonOk, false);
	}
}

This helper method is used to mark the save icon into a disable state. At this moment, this is not really used but if validation is added we could still have the button add without having to remove it until the user fix the problem.

	
function htmlElementWithIconState($element, disabled) {
    $element.prop("disabled", disabled);
    $element.find('.glyphicon').css('opacity', (disabled === true) ? .4 : 1);	
}

Finally, we have the okay button hit which close up the text box and every buttons. In real life, a callback into a real save or okay code would be executed. If successful than close, otherwise keep everything open for the user to adjust his or her input.

	
function onOk(jqueryEvent) {
	var data = jqueryEvent.data;
	var $input = data.input;
	var $buttonOk = data.buttonOk;
	
	onToggle(jqueryEvent);
}
#toggleButton,
#okButton
 {
    padding:0 2px 4px 2px;         
    margin-left:3px;               
    height: 22px;                  
    width: 22px;                   
    vertical-align: top;           
}


#toggleButton span.glyphicon
{
    transition: all 1000ms ease;
}


#okButton {
    transition: all 1000ms ease;
}


.hide-input-inline {
    width:0;
    transition: width 1000ms ease-in-out;
}


.show-input-inline {
    width:210px;
    transition: width 1000ms ease-in-out;
}


.add-to-close span {
    transform: rotate(135deg);
}


.hide-ok-button {
    opacity:0;

}


.show-ok-button {
    opacity:1;
}

	
#inline-editor-textbox::-webkit-input-placeholder { /* WebKit browsers */
    color:#7f7f7f

}
#inline-editor-textbox {
    border: none;
    background-color: #E2E2E2;
    color:#7f7f7f;
    padding-left:4px;
    height:22px;/*To fix the size of the button since we do not have any border*/
}

#inline-editor-textbox:focus {
    outline: none; 
    background-color:white; 
}

Bootstrap Loading Spinner With CSS3

If you are using Bootstrap library and are using the button to load something from Ajax you may want to have the button to be disable and display a waiting message. The easiest way to do is to use the button with the data-loading-text attribute. This allow to use the button method to have the text in the attribute to be placed inside your button and once it is done to call again the button method to have the text reset back to the original value.

<button id="buttonSelector" 
        class="btn btn-primary" 
        data-loading-text="... Loading ...">
        Do long action here</button>

The JavaScript:

$("#buttonSelector").click(function () 
{
     $(this).button('loading');
     // Long waiting operation here
     $(this).button('reset');
}
);

So far, the text is changing but their is not animation. A trick is to use a glyphicon, available with Bootstrapper, and to make this one animate with CSS3. The first modification is to set the data-loading-text attribute with the glyphicon code. This mean that we will set html into the attribute.

<button id="buttonSelector" 
        class="btn btn-primary" 
        data-loading-text="<span class='glyphicon-left glyphicon glyphicon-refresh spinning'></span>... Loading ...">
        Do long action here</button>

The JavaScript remains the same but a new addition is required in the CSS.

.glyphicon.spinning {
    animation: spin 1s infinite linear;
    -webkit-animation: spin2 1s infinite linear;
}

@keyframes spin {
    from { transform: scale(1) rotate(0deg);}
    to { transform: scale(1) rotate(360deg);}
}

@-webkit-keyframes spin2 {
    from { -webkit-transform: rotate(0deg);}
    to { -webkit-transform: rotate(360deg);}
}

.glyphicon-left {
    margin-right: 7px;
}

The animation is 1 second long and is linear which mean that during the 1 second the animation will remain constant. The spin animation is a transform on the rotation from 0 degree to 360 degree which is a complete rotation. Here is the end result.

BootstrapLoadingAnimationButton.gif

CSS Stacking Context

If you are only using z-index to set the depth position of html elements, than you may reach the situation of not having the final behavior your want. Z-index is a Css’ property for the order top-bottom in the z axis. What most people do not know is that it is not an index that works for the entire page. It works only by context.

Most of the time, z-index works as intended because you are not changing the Css position property. It is static by default, and since everything is static than the z-index is “global” to your webpage, in fact the context is set the the root element which is the html element tag. The behavior change when you start changing the position to something absolute or relative. Changing the position to either absolute or relative and by setting the z-index to something else than the default value “auto”, generate a new stacking context. This mean that the z-order beyond that point is resetted. Everything inside the html element of this new position restart. You can see that like different containers. So, you can have your global html, and two elements that both of them have a position and z-index that create two new stacking context. Every z-index set inside these two containers are just for the container itself. That mean that if you have an element inside one of these container that is also set has relative or absolute and that this one goes beyond the boundary of the container that this one may appear behind the next container. Here is a small code to illustrate.

<div class="parent">Parent
    <div class="kid kid1">Kid1
        <div class="kid-above-all">
            <div class="aboveall">AboveAll</div>
        </div>
    </div>
    <div class="kid kid2">Kid2</div>  
</div>
.parent{
    position:relative;
    background-color:blue;
    width:650px;
    height:400px;
}
.kid{
    position:absolute;
    background-color:yellow;
    width:300px;
    height:100px;
    z-index:2; 
}
.kid1{left:10px;}
.kid2{left:330px;}
.kid-above-all{
    position:relative;
    width:20px;
    height:0;
    z-index:10000;
}
.aboveall{
    position:fixed;
    width:550px;
    height:30px;
    left:150px;
    top:30px;
    background-color:green;
    border:solid 2px black;
    z-index:20000;
}

The result is that kid2 container is hidding the AboveAll division. Even if aboveall and kid-above-all has a huge z-index, it is still behind kid2. The reason is that the z-index used by these two elements are only valid for the kid1 stacking context.

CssStackingContextZ-index1

To fix that, you need to set the container z-index to something bigger than the other stacking context. In that case, we want kid1 div to have a higher z-index value than kid2.

.parent{
    position:relative;
    background-color:blue;
    width:650px;
    height:400px;
}
.kid{
    position:absolute;
    background-color:yellow;
    width:300px;
    height:100px;
    z-index:2; 
}
.kid1{left:10px; z-index:3};
.kid2{left:330px;}
.kid-above-all{
    position:relative;
    width:20px;
    height:0;
}
.aboveall{
    position:fixed;
    width:550px;
    height:30px;
    left:150px;
    top:30px;
    background-color:green;
    border:solid 2px black;
}

CssStackingContextZ-index2

Here is the JSFiddle:

There is other action than setting a position to absolute or relative with a z-index value that can trigger the creation of a new stacking context. If you are using flex item with a z-index, than you will have the same behavior: a new CSS stacking context. This one is less frequent. Another possibility is to set the opacity value less than 1 or use a transform with a value that is different than the default “auto”. The opacity and transformation properties are more and more used which require even more to understand what is CSS stacking.

To close the loop, z-index is only valid inside a CSS stacking context. A stacking context is created depending of how some specific CSS properties are set. If you want to have an inner html element above another element from another stacking context, than you must change the z-index of the stacking context itself and not the element one.

Css3 shining animation for Html element

In the current application I am developing, I wanted to have an Html element to have a shining effect with CSS3. The goal is to make an Html’s element to look new. Here is an animated gif that show the final result.
AnimationDiv

This animation must be set by setting a class to any Html element that we want the animation. For my purpose, it was a link element, but it could be a Div or an Li without problem. Once the class is set to the element you want, this one must run in an infinite loop. This is done by setting a custom class the CSS3 animation. This example work only for Chrome but you can define additional vendor prefix than webkit. The first line ensure that the animation will take place on the whole width of the Html element where we add the class. Then, we specify which animation we want to run, the duration of the animation, that we want to run in infinitely and the animation effect by setting a cubic-bezier tempo.

.shine-me {
    width:100%; /*Make sure the animation is over the whole element*/

    -webkit-animation-name: ShineAnimation;
    -webkit-animation-duration: 5s;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-timing-function: cubic-bezier(.12,.89,.98,.47);
}

The animation goes from an initial state to an ending state. What we want is to move an background-image that we define totally in CSS by creating a linear-gradient. What we want is to have a transparent color that goes to a white color in the middle and go back to a transparent color. We then move from a position outside the vision to a position out of vision.

@-webkit-keyframes ShineAnimation{
    from {
        background-repeat:no-repeat;
        background-image:-webkit-linear-gradient(
            top left,
            rgba(255, 255, 255, 0.0) 0%,
            rgba(255, 255, 255, 0.0) 45%,
            rgba(255, 255, 255, 0.5) 48%,
            rgba(255, 255, 255, 0.8) 50%,
            rgba(255, 255, 255, 0.5) 52%,
            rgba(255, 255, 255, 0.0) 57%,
            rgba(255, 255, 255, 0.0) 100%
        );
        background-position:-250px -250px;
        background-size: 600px 600px
    }
    to {
        background-repeat:no-repeat;
        background-position:250px 250px;
    }
}

This code has obviously some flaws. First of all, it does not scale very well with big Html element. This is due mainly because of the background-position that is set the specific pixel position. The second flaw is the color of the shining animation. If the background of the Html element is too bright, than we do not see the shining effect, if it is too dark, the shining effect looks fake.


You can find the code and a demo in this JsFiddle : http://jsfiddle.net/kg2fw40v/.