Monday, September 28, 2020

CSS Position Sticky - Recent Trend in Cross Browser Web Development

Seven to eight years back CSS developers dropped another child to the positioning element which already had four children. The name of this element was “sticky” because all it does is getting stick to the viewport and just be in your sight all the time (depending on the developer though). Although the sticky property of an element gives a particular name to a particular property in CSS, it does not bring anything “new” to the table. I mean, if currently, I say, “let’s use a sticky div box”, you know what I am talking about but before its release people would just define what they wanted to do like “Can I have a div box that would be always visible or available even the people are scrolling?.” Well, the reason why I brought it up is to tell you that stickiness existed in the web development long before it was introduced as a standard in CSS. In this post, we will stick to the CSS property only but it is better to briefly see how people used the sticky property before its release. 

 

Sticky elements are predominantly used for keeping something shown on the screen throughout scrolling. As cool as that is, we can also hide elements in the same way!

 

According to MDN:

 

Sticky positioning is a hybrid of relative and fixed positioning. The element is treated as relative positioned until it crosses a specified threshold, at which point it is treated as fixed positioned”.

Need for Sticky Property In CSS 

As I mentioned, the sticky property was used even before it came as a standard in CSS. So, why did they introduce it when everything was working fine? 

Apart from CSS, the stickiness can be achieved through JavaScript also. In JavaScript, we make the use of scroll event handlers and calculate the offset of the page. With these values we make calculations to stick the element as soon as the offset reaches a point.

This was used to work in those times but for the last eight-nine years, scroll handler was a mess when better graphics were introduced in the systems. 

The problem with scroll handlers is that unlike CSS, it relies on CPU for doing its job. CSS, on the other hand, uses hardware acceleration (a standard on all the browsers now) which means it relies on the GPU for doing its job. Due to this, we would often see the UI of the website breaking easily when the sticky element is coded in JavaScript.

 A better solution to this is, bring the stickiness to the GPU and the only way to do that is by introducing it as a standard in CSS. Looking back, it actually makes a lot of sense. So, the “sticky” property was added to the positions which already had four values. To understand “sticky”, we should know the behaviour of other values.

 CSS Position and Its Values 

 The position attribute in CSS is used to define the position of the element it has been used on in the browser window. With CSS positions, you can manipulate how the element behaves using different values of this property.

The position property in CSS postulates the type of positioning method used for an element.

Before the value “sticky” came into the picture, CSS: Position had four different values: 

Static:  The element with a static value remains with the natural flow of the document. Specifying positions through the top, left, right etc will have no effect on this element. This is also the default behaviour of an element in HTML.

 Example:

 div.static {

  position: static;

  border: 3px solid #73AD21;

}

 Output:

Relative: The relative value is the same as the static value but now the left, right, top, bottom values will affect the position of the element. So, the position of the element will become relative to its default position and hence the word relative. Although, it is important to remember that moving this element will not affect other elements and they will still remain in their actual position and actual space.

Absolute: The absolute value of CSS: Position takes the element out of the normal flow of the page and searches for the closest parent (ancestor) which is available with the position set to either relative or absolute. When such an ancestor is found, this element is moved relative to this ancestor by using left, right, top, bottom specified values. If there is no such ancestor that has this property, the default ancestor will become <html> element and this element will be placed relative to <html> i.e. the web page itself.

An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed). However, if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.

Example Showcasing Absolute & Relative Position in CSS.

Relative: The relative value is the same as the static value but now the left, right, top, bottom values will affect the position of the element. So, the position of the element will become relative to its default position and hence the word relative. Although, it is important to remember that moving this element will not affect other elements and they will still remain in their actual position and actual space.

Absolute: The absolute value of CSS: Position takes the element out of the normal flow of the page and searches for the closest parent (ancestor) which is available with the position set to either relative or absolute. When such an ancestor is found, this element is moved relative to this ancestor by using left, right, top, bottom specified values. If there is no such ancestor that has this property, the default ancestor will become <html> element and this element will be placed relative to <html> i.e. the web page itself.

An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed). However, if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.

Example Showcasing Absolute & Relative Position in CSS.

 <!DOCTYPE html>

<html>

<head>

<style>

div.relative {

  position: relative;

  width: 400px;

  height: 200px;

  border: 3px solid #73AD21;

}

 div.absolute {

  position: absolute;

  top: 80px;

  right: 0;

  width: 200px;

  height: 100px;

  border: 3px solid #73AD21;

}

</style>

</head>

<body>

 <h2>position: absolute;</h2>

 <p>An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed) :</p>

 <div class="relative">This div element has position: relative;

  <div class="absolute">This div element has position: absolute;</div>

</div>

 </body>

</html>

 Output: 


Fixed: An element with the fixed property is fixed with respect to the container block which most of the times is the browser’s window also called the viewport. The benefit of having a fixed element is that it does not move even though you scroll the window. The best example is the navigation bar, which is fixed by the developers at a single place most of the times. But, it should be noted that the container block is not always the viewport of the browser. The container element can change if any of the ancestors of the fixed element has a transform, perspective or filter property set to something else other than none. In such cases, this ancestor becomes the container block and the fixed element’s behaviour changes accordingly. When the block position is identified, the final position depends on the top, left, right, bottom properties only. 

Sticky: A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position: fixed).

CSS z-index Property

This property stipulates the vertical stack order of an element which overlaps with another element.

An element with greater stack order is always in front of an element with a lower stack order.

Key Point: It only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky).

Syntax:

z-index: auto|number|initial|inherit;

How to use Z-index property?

Sample Code:

 <!DOCTYPE html>

<html>

<head>

<style>

img {

  position: absolute;

  left: 10px;

  top: 10px;

  z-index: -1;

}

</style>

</head>

<body>

 <h1>The z-index Property</h1>

 <img src="w3css.gif" width="100" height="140">

<p>Because the image has a z-index of -1, it will be placed behind the heading.</p>

 </body>

</html>

Output:

                                                                    Source: w3schools



Property Values

 auto: Sets the stack order equal to its parents. This is the by default one.

number: Sets the stack order of the element. Negative numbers are allowed

initial: Sets this property to its default value

inherit: Inherits this property from its parent element          

 CSS without z-index:

 <!doctype html>

<html>

  <head>

    <link rel="stylesheet" type="text/CSS" href="style.css">

  </head><body>

      <div class="yellow__box"></div>

      <div class="red__box"></div>

      <div class="orange__box"></div>

  </body>

</html>

. yellow__box {

  position: absolute;

  width:300px;

  height:300px;

  background: yellow;

}. red__box {

  top:60px;

  left:60px;

  position: absolute;

  width:300px;

  height:300px;

  background: red;

}. orange__box {

  top:120px;

  left:120px;

  position: absolute;

  width:300px;

  height:300px;

  background: orange;

}

Output:

If z-index is not set properly, your elements might overlap like this:


The floating behavior of fixed and absolute often causes problems in designing the user interface unknowingly or when the developer does not have prior knowledge. Since these elements are set relative to some other element in the HTML, they sometimes overlap other elements partially or fully and hides those elements. Actually, it is really impossible to note down the number of situations where you can go wrong while designing a web page. Every time, there is something different happening in the code. In the case of positions, the developer is often sure about the static and relative elements since they are always on the natural flow of the document and do not depend on other elements but fixed and absolute should be used very carefully.

What is Sticky position?

The fifth value of the CSS: Position that came after all of the values discussed above is the sticky value. A sticky element toggles between the relative value and the fixed value on the viewport. The state on which the sticky element is currently present depends on the scroll position of the browser window.

The position of the sticky element depends upon the given offset or a threshold top, bottom, left and right value that the developer provides. If the element has not yet reached the threshold, it retains in the relative position. Once the threshold is reached, the position becomes fixed and the elements get “stuck” to the same block. This is not a one-time operation though. The sticky element toggles between these two positions depending on the scroll of the page. So, a sticky element which is currently “fixed” will move back to the “relative” when it will meet the opposite end of its container block.

How To Create A Sticky Element Using CSS?

Creating a sticky element in CSS as I did above is very easy. We just have to keep in mind two things:

  • Declaring the position value as sticky for the element.
  • Defining a relative value (also called the threshold value).

  How To Design A Sticky Header In CSS

 A sticky header can be used to stick the heading of a paragraph to the browser window. So, if the paragraph changes and so does it’s heading, a new heading gets stick to the browser until the user scrolls the complete paragraph. The following code has been used to create a sticky header:

 <!DOCTYPE HTML>

 <head>

<title>Sticky Element </title>

<style>

#sticky-div {

   position : sticky;

            top :0;

  font-size: 30px;

  color: white;

  background-color:  #3991bd;

}

 p {

   font-size: 20px;

}

 #description {

 background-color: #6ccde6;

width : 75%

}

 </style>

 </head>

 <body style = "background-color: #3991bd">

  <center>

<h1 id="sticky-div">Introduction To Sticky Elements In CSS </h1>

<p id = "description">

<br><br>

“Your Text”

<br><br>

</p>

<h1 id="sticky-div">

What is Sticky position?

</h2>

<br><br>

 <p id = "description">

“Your Text”

</p>

<br><br>

<p id = "description">

“Your Text”

</p>

</body>

</html>

In the above code, I have made the element sticky with the id = ”sticky-div”. In the styling part, to make this element sticky, I have given top:0 because I don’t want any gap between the sticky element and viewport boundary. 

Position: sticky specifies that I need to have this element as sticky. With these two parameters, you can make your element sticky in no time. The above-coded web page looks as follows:



 In above figure I have shown that My Header is a sticky element which is being fixed at the  top.

How To Design A Sticky Footer In CSS

 Footer on a website is a great way to let the user catch an eye on something that you want them to see every time they load the website and even without scrolling. In the below example, consider an article where I want the author’s name to be visible all the time. You can use the same code as above with a slight adjustment to make the heading as a footer.

 <!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width, initial-scale=1">

<style>

.footer {

   position: fixed;

   left: 0;

   bottom: 0;

   width: 100%;

   background-color: red;

   color: white;

   text-align: center;

}

</style>

</head>

<body>

 <h2>Fixed/Sticky Footer Example</h2>

<p>The footer is placed at the bottom of the page. </p>

 <div class="footer">

  <p>Footer</p>

</div>

 </body>

</html> 

 The footer will look as follows:

How To Design A Sticky Image In CSS

Sometimes, we want to describe something along with an image that is relevant to the description. But while scrolling, we lose the image and just the text remains. If the text is describing the image, its meaning or its details, the users might be forced to scroll up and down repeatedly to look at the image and then look at the text. This is annoying as a user experience and bad development practice on the developer’s part. Can we adjust something with sticky positions to change the user’s experience in such situations?

 Make the following adjustments in the above code:

 <!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width, initial-scale=1">

<style>

img.sticky {

  position: -webkit-sticky;

  position: sticky;

  top: 0;

  width: 200px;

}

</style>

</head>

<body>

 <h2>Sticky Image: Scroll Down to See the Effect</h2>

<p>The image will "stick" to the screen when you reach its scroll position.</p>

<img class="sticky" src="img_avatar.png" alt="Avatar">

<h2>Scroll Down</h2>

<p>Some example text..</p>

<p><b>Scroll back up again to "remove" the sticky position.</b></p>

<p>Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.Scroll back up again to "remove" the sticky position.</p>

 </body>

</html> 


Special Case with CSS Sticky

While working on a few websites when I discovered the sticky behaviour, I often encountered a hidden problem. The problem was that even though I specified the position and threshold, sticky won’t work!! I have seen a lot of developers commit these mistakes (even experienced ones) and the internet is filled with such questions. This is very important to note that if the sticky element has a parent container and that parent has a property overflow: hidden, then the stickiness won’t work. To make the sticky work in such cases, you need to either give another value to the overflow or remove the overflow property completely.


 Precedence In Sticky Position

A quick question might pop-up in a web developer’s mind about the precedence of the position that the sticky element takes. For example, what if I specify a top threshold as well as a bottom one? The element can’t stick to both the ends, right? So, how do things work out?

When such cases arise, the sticky position follows the precedence rule in order to give preference to one threshold value amongst the specified. The precedence rule is as follows:

 

  • If the developer has specified both the top and bottom values, top values win.
  • If the developer has specified both the left and right values then:
    • Left wins if the direction specified is ltr (left to right).
    • Right wins if the direction specified is rtl (right to left).

 

Direction here refers to the writing direction like Arabic is rtl (right to left) while English is ltr (left to right). You can visit CSS Writing Modes to gain more on that.

Accessibility Issues with CSS Sticky

If we think for one second how sticky position must work then it would not be too hard to conclude that our browser has to do a lot of work when something is “sticky” or maybe “fixed”. When the user scrolls the window, the fixed or the sticky element has to be repainted onto the screen every time. Although it looks as if the element is stuck onto the window, in reality, the browser has to paint it again and again with respect to the scenarios (like different text scrolling behind the headings). If the browser fails in its speed here, then the element would look a little distorted. The problem here is with people with accessibility concerns like sensitivity issues. 

We can help from our side though. To render the element in its own layer and improve the repaint speed we can add will-change: transform along with the sticky properties.

Browser Support for Sticky Positions

The current browser support for CSS Position: sticky is really great. All the major browsers support sticky position except for internet explorer and opera mini.

                                                                        Source: levelup.gitconnected

If you notice the above image, although currently, all the browsers support this feature, but the support came too late considering the basic design implementation it provides like Google Chrome supporting it from version 56, Firefox from 59 and so on. This makes us wonder, how common is sticky position on the web?

Why Don't We Use Sticky Positions That Much?

Looking at what sticky position has to offer in web development, they are used considerably less by the web developers today and I am not counting the big firms or established platforms with dedicated teams. The sticky position came at the right time on the internet but the browser support for it came too late. Seeing no browser support, developers didn’t want to use it on their websites and projects. Till the time the major browser rolled out their updates with sticky position support, it was out of the race. Being in the sand for so long made developers forget about it. On the other hand, stickiness does sometimes behave inappropriately as in the case of overflow property. But, on the positive side, stickiness has started to turn up on many websites even though the number is too small. I hope to see it gain speed in a couple of years. 

Conclusion

CSS Position sticky gives us something that the developers have been using for too long but with too much trouble. Although the sticky property came a long time back, it did not get much appreciation from the browsers. The most used browser in the world, Google Chrome, provided support for sticky positions as late as 2017 i.e. 4 years after Safari gave its support. So, if I take Google Chrome as a reference, I find the sticky position a fairly new property (just from the usage point of view). Seeing this, the web developers have not been using it on their website in the past but, this trend is changing now. The sticky position is taking up pace in the market and with good new designs, it is used in very innovative ways. CSS positions sticky also uses GPU to provide better accessibility for the people who need it. In this post, I have taken you to the depth of sticky with some special cases and concerns. While I wrap this post up here, I would be glad to see some comments on your experience with the sticky property of CSS positions.


@Copyright - Jupitor IT & Research Consulting (P) Ltd.

2 comments:

  Is Corona infection Pandemic a help or plague to the Indian Digital Payments Landscape? With the world surrounded around the worldwide pan...