The CSS position property | Definition & Usage, Syntax, Types of Positioning | List of All CSS Position Properties

The CSS position property

In this tutorial, we will be learning completely about the CSS Position Property and its syntax along with some examples. These details will help you a lot to understand the concept of position property in CSS.

What is the CSS position property?

The CSS position property determines the position of an element in a document. This property runs with the left, right, top, bottom, and z-index properties to define the final position of an element on a page.

Syntax:

position: static|absolute|fixed|relative|sticky|initial|inherit;

The position property can help us to manipulate the location of an element, for example:

.element {
  position: relative;
  top: 20px;
}

Relative to its original position the element above will now be nudged down from the top by 20px.

relative is only one of six values for thepositionproperty. Other values are:

Property Values

  • static: every element has a static position by default, so the element will stick to the normal page flow.
  • relative: an element’s original position remains in the flow of the document, just like thestaticvalue.
  • absolute: the element is removed from the flow of the document and other elements will behave as if it’s not even there whilst all the other positional properties will work on it.
  • fixed: the element is removed from the flow of the document like absolutely positioned elements.
  • sticky (experimental): the element is treated as a relative value until the scroll location of the viewport reaches a specified threshold, at which point the element takes a fixed position where it is told to stick.
  • inherit: the position value doesn’t cascade, so this can be used to specifically force it to, andinheritthe positioning value from its parent.

Also Read: The CSS Display property

Types of Positioning in CSS

A positioned element is an element whose computed position value is eitherrelative, absolute, fixed, or sticky. The default one isstatic, let’s see about it first.

Static

This is a by default position for HTML elements. It constantly positions an element as pert the normal flow of the page. It is not affected by the top, bottom, left, and right properties. Let’s use an example to show thatposition: statichas no effect on the position of an element.

<html>
    <body>
        <div class="parent-element">
            <div class="sibling-element">
                I'm the other sibling element.
            </div>
            
            <div class="main-element">
                All eyes on me. I am the main element.
            </div>
            
            <div class="sibling-element">
                I'm the other sibling element.
            </div>
        </div>
    </body>
<html>

Now, we will addposition: staticto the div with the class main-element and left, top values to it.

.main-element {
    position: static;
    left: 10px;
    bottom: 10px;
    background-color: yellow;
    padding: 10px;
}

.sibling-element {
    padding: 10px;
    background-color: #f2f2f2;
}

Result:

result of static positioning property in css

Absolute

If a child element has an absolute value then the parent element will behave as if the child isn’t there at all:

.element {
  position: absolute;
}

absolute

And when we try to set other values such as leftbottom, and right we’ll find that the child element is responding not to the dimensions of its parent, but the document:

.element {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
}

absolute with position

Relative

We can use position relative to make the child element positioned absolutely from its parent element we need to set this on the parent element itself:

.parent {
  position: relative;
}

Now properties such as leftrightbottom and top will refer to the parent element, so that if we make the child element transparent we can see it sitting right at the bottom of the parent:

relative with position

Fixed

It is very similar to absolute as it can help us to position an element anywhere relative to the document.

But this value is unaffected by scrolling.

Example: 

.sibling-element {
    background: #f2f2f2;
    padding: 10px;
  border: 1px solid #81adc8;
} 

.main-element {
    position: fixed;
    bottom: 10px;
    left: 10px;
    background-color: yellow;
    padding: 10px;
}

.parent-element {
    position: relative;
    height: 100px;
    padding: 10px;
    background-color: #81adc8;
}

html {
    height: 800px;
}

Sticky

This one is introduced recently and the browser support for this is very poor.

The one case where this property is very useful is Navbar where the navbar will appear to the top even after we scroll to the bottom of the page.

#one { position: sticky; top: 10px; }

All CSS Position Properties

No. Property Description Values
1) bottom It is used to set the bottom margin edge for a positioned box. auto, length, %, inherit
2) clip It is used to clip an absolutely positioned element. shape, auto, inherit
3) cursor It is used to specify the type of cursors to be displayed. url, auto, crosshair, default, pointer, move, e-resize, ne-resize, nw-resize, n-resize, se-resize, sw-resize, s-resize, w-resize, text, wait, help
4) left It sets a left margin edge for a positioned box. auto, length, %, inherit
5) overflow This property is used to define what happens if content overflow an element’s box. auto, hidden, scroll, visible, inherit
6) position It is used to specify the type of positioning for an element. absolute, fixed, relative, static, inherit
7) right It is used to set a right margin edge for a positioned box. auto, length, %, inherit
8) top It is used to set a top margin edge for a positioned box. auto, length, %, inherit
9) z-index It is used to set stack order of an element. number, auto, inherit

CSS Media Queries and Responsive Design | Responsive Web Design – Media Queries in CSS with Examples

CSS Media Queries and Responsive Design

Media and responsive queries matter as they can change the view of a website on a desktop platform and also in a mobile platform to use the viewport much better. Just follow the below-provided links and understand what are CSS Media Queries and Responsive Design.

CSS Media Queries

All the above rules we saw are applied to@importor to thelinkHTML tag can be used inside the CSS, too.

You should wrap them in a @media () {} structure.

Example:

@media screen and (max-width: 800px) {
  /* enter some CSS */
}

Moreover, this is the basis for responsive design.

Media queries can be pretty challenging. But this example implements the CSS only if it’s a screen device, the width is between 600 and 800 pixels, and the orientation is the landscape:

@media screen and (max-width: 800px) and (min-width: 600px) and (orientation: landscape) {
  /* enter some CSS */
}

Do Refer: 

How do you write media queries in CSS for Responsive design?

The syntax for CSS media queries relates to TestNG annotations which as a novice web developer, you will obtain a bit different & unique. The media query can be performed by the word “media” as shown below:

@media <media_type> connector ( <query> )

As an example:

@media only screen and (max-width: 480px) {
  /* CSS rules to apply /*
}

This media query will see for screens (“only screen” as addressed) with a max-width of 480px. If it attains one, the conditions will be performed and the changes will be addressed to the HTML code.

If we just use the media type and not the media expressions (queries), the following values are accepted:

  • all
  • print
  • screen
  • speech
@media print {
   .heading {
     font-size: 12px
   }
}

The above query will obtain the content with the class name heading to a font size of 12 pixels when the page wants to be printed.

Media types

In media queries and @import declarations, we can use media types that allow us to determine on which media a CSS file, or a piece of CSS, is loaded.

Media types are:

  • all means all the media
  • print used when printing
  • screen used when the page is presented on a screen (default)
  • speech used for screen readers

Example:

@import url(myfile.css) screen;
@import url(myfile-print.css) print;

/* OR */

@import url(myfile.css) screen, print;

It can also be used in the link tag of an HTML page, like:

<link rel="stylesheet" type="text/css" href="another.css" media="screen, print" />

Media feature descriptors

These additional keywords are used to express more conditionals. These are:

  • width
  • height
  • device-width
  • device-height
  • aspect-ratio
  • device-aspect-ratio
  • color
  • color-index
  • monochrome
  • resolution
  • orientation
  • scan
  • grid

They have a min-* and max-* property, like:

  • min-widthmax-width
  • min-device-widthmax-device-width

The values they consume are px, em, rem, or any length values.

Example:

@import url(myfile.css) screen and (max-width: 800px);

We can also specify the orientation of the device, like:

<link rel="stylesheet" type="text/css" href="myfile.css" media="screen and (orientation: portrait)" />

We can use the scam property to determine the types of screens. Acceptable values are progressive and interlaced.

The color CSS media feature can be used to test the number of bits per color component (red, green, blue) of the output device. This takes an integer value as input. Like this, there are other properties like gridcolor-indexmonochrome.

There are other values like aspect-ratio and device-aspect-ratio , that accept a ratio value representing the width to height viewport ratio, which is expressed as a fraction.

@import url(myfile.css) screen and (aspect-ratio: 4/3);

Also, there is resolution which represents the pixel density of the device, expressed in a resolution data type like dpi.

@import url(myfile.css) screen and (min-resolution: 100dpi);

Logic operators

We can combine multiple queries with logical operators like and, or(can use , instead) not.

Example:

/* and */
<link rel="stylesheet" type="text/css" href="myfile.css" media="screen and (max-width: 800px)" />

/* or */
@import url(myfile.css) screen, print;

/* not */
@import url(myfile.css) not screen;

How to style lists using CSS | CSS Styling Lists | The list-style property in CSS

How to style lists using CSS

To show some data in web pages consists of showing a list altogether. We can override the default style for the list and put our style manually using CSS. Look at the links available here and learn how to style lists using CSS. Also, you may get an idea about the CSS Properties for styling lists from this tutorial.

Basic Styling in CSS

Colouring, padding, margin, and other basic styling can be used to the list and its items:

ul {
    background: #FF888E;
    padding: 25px;
}
ul li {
    background: #45597E;
    margin: 25px;
    color: #FFFFFF;
}

Output:

basic css styling example result

Do Refer:

How to style a list in CSS?

By following the three CSS properties shown here helps to modify the list:

  1. list-style-type
  2. list-style-image
  3. list-style-position

1. list-style-type Property

list-style-type is used to set a predefined marker to be used by the list:

li {
  list-style-type: square;
}

We can also use the disc, circle, or none in place of the square.

2. list-style-image Property

list-style-image is used to use a custom image as a marker, when a predefined marker is not appropriate:

li {
  list-style-image: url(list-image.png);
}

3. list-style-position Property

list-style-position lets us add the marker outside or inside of the list content, in the flow of the page rather than outside of it.

li {
  list-style-position: inside;
}

CSS list-style Property

The list-style lets you specify all the list properties into a single expression. These properties can perform in any order. We can use the shorthand property i.e list-style to specify all the properties altogether:

li {
  list-style: url(list-image.png) inside;
}

Check out the following example:

<html>
   <head>
   </head>
   
   <body>
      <ul style = "list-style: inside square;">
         <li>Maths</li>
         <li>Social Science</li>
         <li>Physics</li>
      </ul>
      
      <ol style = "list-style: outside upper-alpha;">
         <li>Maths</li>
         <li>Social Science</li>
         <li>Physics</li>
      </ol>
   </body>
</html>

Result:

list-style property example output

CSS marker-offset Property

The marker-offset property enables you to define the distance between the marker and the text concerning that marker. Regrettably, this property is not maintained in IE 6 or Netscape 7. Its value must be a length as shown in the below example −

<html>
   <head>
   </head>

   <body>
      <ul style = "list-style: inside square; marker-offset:2em;">
         <li>Maths</li>
         <li>Social Science</li>
         <li>Physics</li>
      </ul>
      
      <ol style = "list-style: outside upper-alpha; marker-offset:2cm;">
         <li>Maths</li>
         <li>Social Science</li>
         <li>Physics</li>
      </ol>
   </body>
</html>

It will result like below:

css styling lists example output

CSS Pseudo Classes | What are Pseudo Classes in CSS? | Syntax & Example Programs on Pseudo-classes

CSS Pseudo Classes

What are CSS Pseudo-classes?

Pseudo-classes are predefined keywords.

They are used to select an element based on its state or to target a specific child.

They start with a single colon :.

The most common use case is to style the visited and unvisited links. Also, focus or hover over an element.

The popular pseudo-classes are:

Classes Description
:active an element is activated by the user (e.g. clicked). Mostly used on links or buttons
:checked a checkbox, option, or radio input types that are enabled
:default the default in a set of choices (like an option in a select or radio buttons)
:disabled an element disabled
:empty an element with no children
:enabled an element that’s enabled (opposite to :disabled)
:first-child the first child of a group of siblings
:focus the element with focus
:hover an element hovered with the mouse
:last-child the last child of a group of siblings
:link a link that’s not been visited
:not() any element not matching the selector passed. E.g. :not(span)
:nth-child() an element matching the specified position
:nth-last-child() an element matching the specific position, starting from the end
:only-child an element without any siblings
:required a form element with the required attribute set
:root represents the html element. It’s like targeting html, but it’s more specific.
:target the element matching the current URL fragment (for inner navigation in the page)
:valid form elements that validated client-side successfully
:visited a link that’s been visited

Also Check:

The :hover pseudo-class

The below sample code shows how to use the :hover class to alter the color of links when we place a mouse pointer over that link. Feasible values could be any color name in any valid format.

<html>
   <head>
      <style type = "text/css">
         a:hover {color: #FFCC00}
      </style>
   </head>

   <body>
      <a href = "">Bring Mouse Here</a>
   </body>
</html>

CSS – The :lang Pseudo-class

The:langpseudo-class enables you to set special rules for various languages.

In the illustration below, :lang represents the quotation marks for <q> elements with lang=”no”:

<html>
<head>
<style>
q:lang(no) {
  quotes: "~" "~";
}
</style>
</head>
<body>

<p>Some text <q lang="no">A quote in a paragraph</q> Some text.</p>

</body>
</html>

The :visited pseudo-class

We want to make a link color yellow, before and after the visit:

a,
a:visited,
a:active {
  color: yellow;
}

The :nth-child pseudo-class

:nth-child() deserves a special mention. It can be used to target odd or even children with :nth-child(odd) and :nth-child(even).

It is commonly used in lists to color odd lines differently from even lines:

ul:nth-child(odd) {
  color: green;
    background-color: gray;
}

We can also use it to target the first 4 children of an element with :nth-child(-n+4). Or you can style 1 in every 7 elements with :nth-child(7n).

CSS classes and pseudo-classes

The classes in CSS can be connected with pseudo-classes. So, we can address it as-

Syntax

selector.class: pseudo-class {  
  property: value;  
}

Let’s see the following example to understand the working of it:

<!DOCTYPE html>
<html>
<head>
<style>
body{
text-align:center;
}
div.hello:hover {
  color: red;
  font-size:40px;
} 
</style>
</head>
<body>
<h1>CSS Classes and pseudo-classes</h1>
<h2>Move your cursor to the below text</h2>
<div class="hello">Hello World</p>

</body>
</html>

Output:

css classes and pseudo-classes example

CSS Pseudo Elements | What is Pseudo Element in CSS? | Syntax & Sample Example

CSS Pseudo Elements

What is CSS Pseudo-elements?

Pseudo-elements act in a similar way, but, they work as if you had added a whole new HTML element into the markup, in place of utilizing a class to existing elements. Pseudo-elements start with a double colon ::.

For instance, it can be applied to:

  • Style an element when a user mouses over it
  • Style visited and unvisited links differently
  • Style an element when it gets focus

They are used to style a specific part of an element and start with a :: .

We also use : as a pseudo-element for backward compatibility.

::before and ::after are probably the most used pseudo-elements. They are used to add content before or after an element, like icons for example.

The pseudo-elements are:

::after creates a pseudo-element after the element
::before creates a pseudo-element before the element
::first-letter can be used to style the first letter of a block of text
::first-line can be used to style the first line of a block of text
::selection targets the text selected by the user

Do Check:

Pseudo Element & Pseudo Class Syntax

The syntax of pseudo-element:

selector::pseudo-element {
  property: value;
}

The syntax of pseudo-classes:

selector:pseudo-class {
  property: value;
}

CSS classes can also be practiced with pseudo-elements −

selector.class:pseudo-element {property: value}

Examples of CSS Pseudo Elements

We want to make the font of the first line of the paragraph slightly bigger than the rest:

p::first-line {
  font-size: 1.5rem;
}

Or maybe we want the first letter to be bigger and bolder:

p::first-letter {
  font-weight: bolder;
  font-size: 2rem;
}

We can specify the content property to insert any kind of content like image, after or before an element:

p::before {
  content: url(/myimage.png);
}

.myElement::before {
    content: "Hey There!";
}

The :after pseudo-element

<html>
   <head>
      <style type = "text/css">
         p:after {
            content: url(/images/bullet.gif)
         }
      </style>
   </head>

   <body>
      <p> This line will be succeeded by a bullet.</p>
      <p> This line will be succeeded by a bullet.</p>
      <p> This line will be succeeded by a bullet.</p>
   </body>
</html>

Output:

pseudo elements in css example

The :before pseudo-element (Decorative example)

HTML Code:

<span class="ribbon">Notice where the orange box is.</span>

CSS Code:

.ribbon {
  background-color: #5BC8F7;
}

.ribbon::before {
  content: "Look at this orange box.";
  background-color: #FFBA10;
  border-color: black;
  border-style: dotted;
}

Output:

result of before pseudo element in css

The :first-line pseudo-element

<html>
   <head>
      <style type = "text/css">
         p:first-line { text-decoration: underline; }
         p.noline:first-line { text-decoration: none; }
      </style>
   </head>

   <body>
      <p class = "noline">
         This line would not have any underline because this belongs to nline class.
      </p>
      
      <p>
         The first line of this paragraph will be underlined as defined in the 
         CSS rule above. Rest of the lines in this paragraph will remain normal. 
         This example shows how to use :first-line pseduo element to give effect 
         to the first line of any HTML element.
      </p>
   </body>
</html>

Output:

css pseudo elements example result

The :first-letter pseudo-element

The resulting example proves how to use the :first-letter element to add unique effects to the first letter of elements in the document.

<html>
   <head>
      <style type = "text/css">
         p:first-letter { font-size: 5em; }
         p.normal:first-letter { font-size: 10px; }
      </style>
   </head>

   <body>
      <p class = "normal">
         First character of this paragraph will be normal and will have font size 10 px;
      </p>
      
      <p>
         The first character of this paragraph will be 5em big as defined in the 
         CSS rule above. Rest of the characters in this paragraph will remain 
         normal. This example shows how to use :first-letter pseduo element 
         to give effect to the first characters  of any HTML element.
      </p>
   </body>
</html>

Output:

example 1 output

The ::selection pseudo element

HTML Code:

This text has special styles when you highlight it.
<p>Also try selecting text in this paragraph.</p>

CSS Code:

/* Make selected text gold on a red background */
::selection {
  color: gold;
  background-color: red;
}

/* Make selected text in a paragraph white on a blue background */
p::selection {
  color: white;
  background-color: blue;
}

Output:

selection css pseudo element example output

The CSS z-index property | Definition, Syntax, Property Values, Example Code on z-index CSS Property

The CSS z-index property

The z-index CSS property estimates the z-order of a positioned element and its descendants or flex items. Look at the below sections to understand the concept of thez-index property thoroughly.

It’s very useful when you have multiple elements that overlap each other, and you need to decide which one is visible, as nearer to the user, and which one(s) should be hidden behind it.

This property takes a number (without decimals) and uses that number to calculate which elements appear nearer to the user, in the Z-axis.

Also Check: 

The higher the z-index value, the more an element is positioned nearer to the user.

When deciding which element should be visible and which one should be positioned behind it, the browser does a calculation on the z-index value.

CSS z-index Property

The z-indexproperty defines the stack order of an element. An element with a more comprehensive stack order is always ahead of an element with a lower stack order. Overlapping elements with a larger z-index defense those with a smaller one.

Remember: On all positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display: flex elements), the z-index property only works.

Formal Definition of z-index CSS

Initial value auto
Applies to positioned elements
Inherited no
Computed value as specified
Animation type an integer
Creates stacking context yes

Syntax for z-index CSS Property

/* Keyword value */
z-index: auto;

/* <integer> values */
z-index: 0;
z-index: 3;
z-index: 289;
z-index: -1; /* Negative values to lower the priority */

/* Global values */
z-index: inherit;
z-index: initial;
z-index: unset;

The z-index property is defined as either the keywordauto or an<integer>.

auto:The box does not set a new local stacking context. The stack level of the created box in the current stacking context is 0.

<integer>:This <integer> is the stack level of the created box in the current stacking context. Also, the box builds a local stacking context. This implies that the z-indexes of descendants are not related to the z-indexes of elements outside this element.

Formal Syntax

auto | <integer>

CSS z-index Property Values

Value Description
auto Sets the stack order equal to its parents. This is default
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.

Using CSS z-index Property

The default value isautoa special keyword. Using auto, the Z-axis order is determined by the position of the HTML element in the page – the last sibling appears first, as it’s defined last.

By default, elements havestaticvalue for thepositionproperty. In this case, thez-indexproperty does not make any difference – it must be set toabsoluterelative or fixed to work.

Example:

.my-first-div {
    position: absolute;
    top: 0;
    left: 0;
    width: 600px;
    height: 600px;
    z-index: 10;
}

.my-second-div {
    position: absolute;
    top: 0;
    left: 0;
    width: 500px;
    height: 500px;
    z-index: 20;
}

The element with class .my-second-div will be displayed, and behind it .my-first-div.

Here we used 10 and 20, but you can use any number. Negative numbers too. It’s common to pick non-consecutive numbers, so you can position elements in the middle. If you use consecutive numbers instead, you would need to re-calculate the z-index of each element involved in the positioning.

Example on Visually layering elements using CSS z-index Property

HTML

<div class="wrapper">
  <div class="dashed-box">Dashed box</div>
  <div class="gold-box">Gold box</div>
  <div class="green-box">Green box</div>
</div>

CSS

.wrapper {
  position: relative;
}

.dashed-box {
  position: relative;
  z-index: 1;
  border: dashed;
  height: 8em;
  margin-bottom: 1em;
  margin-top: 2em;
}
.gold-box {
  position: absolute;
  z-index: 3; /* put .gold-box above .green-box and .dashed-box */
  background: gold;
  width: 80%;
  left: 60px;
  top: 3em;
}
.green-box {
  position: absolute;
  z-index: 2; /* put .green-box above .dashed-box */
  background: lightgreen;
  width: 20%;
  left: 65%;
  top: -25px;
  height: 7em;
  opacity: 0.9;
}

Output:

z-index property example output

How to disable text selection using CSS | user-select Property Definition, Syntax, Values | Steps to Disable Text Selection

How to disable text selection using CSS

Texts are the most fundamental elements of any website or web page. In this tutorial, we have shared how to disable text selection highlighting using CSS? Along with the CSS user-select Property definition and usage, syntax, values,  supported browsers, Steps to disable the text selection with CSS, and Example Codes on How to disable text selection highlighting using CSS?

CSS user-select Property

Theuser-selectproperty defines whether the text of an element can be selected. In various web browsers, in case you double-click on some particular text it will be selected/highlighted. To be unselected or disabled, this property can be used.

Default value: auto
Inherited: no
Animatable: no.
Version: CSS3
JavaScript syntax: object.style.userSelect=”none”

CSS Syntax

user-select: auto|none|text|all;

Do Check:

user-select property values

user-select value description
none user cannot select the text
text user can select the text
all user can select the text with one click
auto user-select value depend upon its parent user-select option
contain selection will be bound to a particular element
element IE version of user-select contain.

How to disable text selection using CSS

By default browsers let us select the text in the browser using the keyboard, pressing the cmd-A combination on a Mac for example, or using the mouse.

How can you disable that, to make your web page behave more like an app and less like a document?

Use the user-select: none; CSS rule.

-webkit-touch-callout: none;
  -webkit-user-select: none;
   -khtml-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;

One thing I use sometimes is to make all the app interface unselectable applying user-select: none; on the body element, then I can re-enable it on specific elements, using:

user-select: text;

Also, observe what statements that we can use for different browsers to disable a selectivity of text.

  • Chrome, Opera: -webkit-user-select
  • Safari: -webkit-touch-callout
  • Mozilla: -moz-user-select
  • Internet Explorer: -ms-user-select

Example on How to disable text selection highlighting in the browsers using CSS?

At present, browsers only assist a small subset of CSS properties for::selection pseudo-element like color, background-color and text-shadow. Let’s see an example:

::selection {
    color: none;
    background: none;
}
/* For Mozilla Firefox */
::-moz-selection {
    color: none;
    background: none;
}

Steps to Disable Text Selection In WebPage Using CSS

There are two steps that should be followed to disable the text selection in webpage using CSS:

  1. Make a HTML file and determine markup for webpage
  2. Make a CSS file and specify styling to disable the text

Step 1: Make a HTML file and determine markup for webpage

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="disable_style.css">
</head>
<body>
  
<h1>Disable Text Selection In WebPage Using CSS</h1>
<p class="select">Select The Text In This Paragraph This Is Selectable Like Any Other Text</p>
<p class="no_select">Try To Select This Text You Are Not Able To Select This Text In Modern Browsers</p>

</body>
</html>

Step 2: Make a CSS file and specify styling to disable the text

In this step, we have used the user-select property to disable the text selection and also the cross-browser prefix to work in most of the browser and also with some old browsers.

body
{
    background-color:#EB99FF;
    font-family:helvetica;
    text-align:center;
    margin:0px auto;
    padding:0px;
}
h1
{
    margin-top:100px;
    color:#424242;
    font-size:40px;
}
h1 p
{
    margin:0px;
    font-size:18px;
    color:black;
    text-decoration:underline;
}
.select
{
    font-size:30px;
    font-weight:bold;
    color:#4000FF;
}
.no_select
{
    font-size:30px;
    font-weight:bold;
    color:#4000FF;
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

How To Animate Using CSS

CSS is able to create basic animations can be seen as a starting point for any amateur who wants to create websites that provide a better user experience.
In this post, I will be talking about how one can get animations using just CSS and simple shapes like squares, triangles, and circles.

@keyframes

@keyframes is the main component of CSS animations. It is THE CSS rule where animations are created.
To make CSS animations work @keyframes is first defined and then bound to a selector.

The animation property in CSS can be used to animate many other CSS properties such as color, background-color, height, or width. Each animation needs to be defined with the @keyframes at-rule which is then called the animation property, like so:

.element {
  animation: pulse 5s infinite;
}

@keyframes pulse {
  0% {
    background-color: #001F3F;
  }
  100% {
    background-color: #FF4136;
  }
}

Animation using CSS

Each @keyframes at-rule defines what should happen at specific moments during the animation. For example, 0% is the beginning of the animation and 100% is the end. These keyframes can then be controlled either by the shorthand animation property or its eight sub-properties, to give more control over how those keyframes should be manipulated.

Sub-properties

  • animation-name: declares the name of the @keyframes at-rule to manipulate.
  • animation-duration: the length of time it takes for an animation to complete one cycle.
  • animation-timing-function: establishes preset acceleration curves such as ease or linear.
  • animation-delay: the time between the element being loaded and the start of the animation sequence.
  • animation-direction: sets the direction of the animation after the cycle. Its default resets on each cycle.
  • animation-iteration-count: the number of times the animation should be performed.
  • animation-fill-mode: sets which values are applied before/after the animation.For example, you can set the last state of the animation to remain on screen, or you can set it to switch back to before when the animation began.
  • animation-play-state: pause/play the animation.

These sub-properties can then be used like so:

@keyframes stretch {
  /* declare animation actions here */
}

.element {
  animation-name: stretch;
  animation-duration: 1.5s; 
  animation-timing-function: ease-out; 
  animation-delay: 0s;
  animation-direction: alternate;
  animation-iteration-count: infinite;
  animation-fill-mode: none;
  animation-play-state: running; 
}

/*
  is the same as:
*/

.element {
  animation: 
    stretch
    1.5s
    ease-out
    0s
    alternate
    infinite
    none
    running;
}

Square To Circle

Let’s create a simple shape transition; a square to circle animation using the above principles. We will have five stages in total and for each stage, we will define a border-radius, a rotation, and a different background color to our element.

HTML:

<div class="element"></div>

CSS:

.element {
  height: 250px;
  width: 250px;
  margin: 0 auto;
  background-color: red;
  animation-name: stretch;
  animation-duration: 1.5s; 
  animation-timing-function: ease-out; 
  animation-delay: 0;
  animation-direction: alternate;
  animation-iteration-count: infinite;
  animation-fill-mode: none;
  animation-play-state: running;
}

@keyframes stretch {
  0% {
    transform: scale(.3);
    background-color: red;
    border-radius: 100%;
  }
  50% {
    background-color: orange;
  }
  100% {
    transform: scale(1.5);
    background-color: yellow;
  }
}

body,
html {
  height: 100%;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
}

 

Square to Circle CSS

Multiple Animations

To add multiple animations, just use a comma separator!

@keyframes fade {
  to {
    opacity: 0;
  }
}
@keyframes rotate {
  to {
    transform: rotate(180deg);
  }
}
.element {
  animation: fade 2s 1s infinite linear alternate,
             rotate 2s 1s infinite linear alternate;
}

Adding Vendor Prefixes

This is actually very important when we add CSS animations. Say you have designed a website full of animations and other stuff that gives a rich user experience. You open it on Chrome and Voila! It works perfectly! But when you open it on Firefox, the animations have crashed!

To avoid this from happening, a developer needs to add vendor prefixes.

The standard prefixes applied are:

  • Chrome & Safari: ~webkit~
  • Firefox: ~moz~
  • Opera: ~o~
  • Internet Explorer: ~ms~

Code will now look like this:

.element {
    -webkit-animation: fade 4s 1s infinite linear alternate;
    -moz-animation: fade 4s 1s infinite linear alternate;
    -ms-animation: fade 4s 1s infinite linear alternate;
    -o-animation: fade 4s 1s infinite linear alternate;
    animation: fade 4s 1s infinite linear alternate;

If we add @keyframes ,

@-webkit-keyframes fade { /* your style */ }
@-webkit-keyframes fade { /* your style */ }
@-webkit-keyframes fade { /* your style */ }
@-webkit-keyframes fade { /* your style */ }
@keyframes fade { /* your style */ }

Performance

Animating most properties is a performance concern, so we should proceed with caution before animating any property.

However, there are certain combinations that can be animated safely:

  • transform: translate()
  • transform: scale()
  • transform: rotate()
  • opacity

How to Create Horizontal Scrolling Containers

Making a scrollbar with or without using the in-built function of CSS is always a good challenge, and making a responsive horizontal scrollbar is taking it further towards perfection. In this blog, you will learn how to make a responsive scroll bar (slider) using CSS library. Let’s get started.

Creating Horizontal Scrolling Containers the Right Way

We all like learning how to make new designs using CSS, but still it is recommended to know some basics of CSS and HTML beforehand before progressing further towards our blog.

Note: There are two ways to make a horizontal scrollbar, one is using the webkit that is included in the CSS library, and the method that we are going to use, that is manual manipulation method using CSS properties as we are aiming on a responsive horizontal scrollbar.

But just for the sake of knowledge, here is the easy way to make a horizontal scrollbar presuming you have written a skeleton HTML code and assigned class(es).

::-webkit-scrollbar {
  width: 10px;
}


::-webkit-scrollbar-track {
  background: #f1f1f1;
}


::-webkit-scrollbar-thumb {
  background: #888;
}


::-webkit-scrollbar-thumb:hover {
  background: #555;
}

So, now getting this out of our way, let’s get started towards making our own.

Skelton HTML

First we shall create a basic HTML file where the CSS styling will be implemented, a skeleton design of a HTML file is more than enough to cater our needs.
I have made a section to keep the container component which is to be displayed on the page.

<section>
        <div class="card">
          <h2>Slider Content</h2>
          <p>
            Lorem ipsum dolor sit amet, consectetur adipiselisdo
            eiusmod tempor incididunt ut labore et dolorealienim
            ad minim veniam, quis nostrud exercitation nisi ut
            aliquip ex ea commodo consequat. Duis aute dolor in
            reprehenderit in voluptate velit esseu fugiat nulla
            pariatur. Excepteur sint occaecat cupidataprosunt in
            culpa qui officia deserunt mollit anim id laborum.
          </p>
        </div>
 </section>

This is just one section, but there are copies of many of the similar sections, to display while scrolling.

data-0="transform:translateX(0%)"
data-1000="transform:translateX(-300%)"

This is the code to make the animation smoother, I used skrollr.
Please refer to the documentation to the references link attached below.

Container Styling

.container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  display: flex;
}

Making it a flex display with position fixed.

Section Styling

.container section {
  min-width: 100%;
  height: auto;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #fffee1;
}

Also flex sectional content with items on the center and height to fit the screen.

N-th Child Property

This is used for randomising the background without writing much code, as even and odd can differentiate and put the background accordingly. In our small project it is written as:

.container section:nth-child(odd) {
  background-color: #fffee1;
}
.container section:nth-child(even) {
  background-color: #fce8f4;
}

Heading and Content Styling

.card h2 {
  margin: 0 0 20px;
  padding: 0;
  font-size: 48px;
  text-transform: uppercase;
  color: #044463;
}

.card p {
  font-size: 20px;
  line-height: 1.4em;
  color: black;
}

This is basic CSS styling for the contents of the card component to scroll through.

Responsive Design:

@media (max-width: 800px) {
  .container {
    position: absolute;
    display: flex;
    flex-direction: column;
    height: auto;
    transform: none !important;
  }
}

So that it is accessible via mobile/tablet devices also.

Result

How to Make a Collapsible Menu using only CSS

There are many ways to design a menubar (or sometimes called as a navbar) with CSS, and it is quite simple and easy to understand. The requirements are that you should know the basic fundamentals of HTML and CSS and you are good to go with the article.

Implementing A Pure CSS Collapsible

In this article, I will show a simple way to make a collapsible menu bar using CSS

Skelton HTML

<div class="collapsible-menu">
    <div class="menu-content">
        <ul>
            <li><a href="#"></a>Home</li>
            <li><a href="#"></a>Services</li>
            <li><a href="#"></a>Projects</li>
            <li><a href="#"></a>About</li>
            <li><a href="#"></a>Blog</li>
            <li><a href="#"></a>Contacts</li>
         </ul>
     </div>
</div>

Next, we’ll add a checkbox with a label of Menu above the div that holds the menu content. We’ll style this later to trigger the opening and closing of the menu.

<body>
        <div class="collapsible-menu">
            <input type="checkbox" id="menu">
            <label for="menu">Menu</label>
            <div class="menu-content">
                <ul>
                    <li><a href="#"></a>Home</li>
                    <li><a href="#"></a>Services</li>
                    <li><a href="#"></a>Projects</li>
                    <li><a href="#"></a>About</li>
                    <li><a href="#"></a>Blog</li>
                    <li><a href="#"></a>Contacts</li>
                </ul>
            </div>
        </div>
    </body>

Here’s what the menu looks like without any style indented.

Let’s add some padding, borders and styles to look more like a menu.

.menu-content {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
         Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
    padding: 0 0 0 50px;
}
.collapsible-menu {
    background-color: rgb(255, 255, 255);
    padding: 0px 30px;
    border-bottom: 3px solid #CDE700;
    box-shadow: 1px 2px 3px rgba(0,0,0,0.2);
}
.collapsible-menu ul {
    list-style-type: none;
    padding: 0;
}
.collapsible-menu a {
    display:block;
    padding: 10px;
    text-decoration: none;
}

It looks similar to this

We’ll style the label for the checkbox by adding a background image for the hamburger menu. We also want to make the label look like it’s a link even though it’s not, so we’ll use . Lastly, we’ll hide the checkbox using .

.collapsible-menu label {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
     Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
    font-size: 56px;
    display: block;
    cursor: pointer;
    background: url(menu.png) no-repeat left center;
    padding: 10px 0 10px 50px;
}
input#menu {
    display: none;
}

After implementation, the result will look similar to this.

NOTE: I have used the menu bar icon from font awesome CDN.

Collapse and Expand

Now we just have to set the default state of the menu to be collapsed when when checkbox is not checked. We do this by changing the max-height of  to , but have it display a  of  when the checkbox is checked.

.menu-content {
    max-height: 0;
    overflow: hidden;
    padding: 0 0 0 50px;
}
/* Toggle Effect */
input:checked ~ label {
}
input:checked ~ .menu-content {
    max-height: 100%;
}

Unchecked:

 

Checked:

Conclusion

That’s it! It’s a really quick and easy way to add a collapsible menubar using only HTML and CSS.