The CSS Padding Tutorial | CSS Padding Property | Syntax & Example Program of CSS Padding Shorthand Property

The CSS Padding Tutorial

Padding is used to create space around an element’s content, inside of any defined borders. Here, you will get to know & understand completely about the CSS Padding along with syntax and example codes.

CSS Padding Property

The padding CSS property is usually used in CSS to add space in the inner side of an element.

Syntax:

/* Apply to all four sides */
padding: 1em;

/* vertical | horizontal */
padding: 5% 10%;

/* top | horizontal | bottom */
padding: 1em 2em 2em;

/* top | right | bottom | left */
padding: 5px 1em 0 2em;

/* Global values */
padding: inherit;
padding: initial;
padding: unset;

Also Refer: 

Define Paddings for Individual Sides

CSS has properties for specifying the padding for each side of an element:

  • padding-top
  • padding-right
  • padding-bottom
  • padding-left
Property Description
padding It is used to set all the padding properties in one declaration.
padding-left It is used to set the left padding of an element.
padding-right It is used to set the right padding of an element.
padding-top It is used to set Top padding of an element.
padding-bottom It is used to set the bottom padding of an element.

All the padding properties can have the following values:

  • length – specifies padding in px, pt, cm, etc.
  • % – specifies padding in % of the width of the containing element
  • inherit – specifies that the padding should be inherited from the parent element

Note: Negative values are not allowed.

CSS Padding Example

<!DOCTYPE html>
<html>
<head>
<style>
div {
  padding: 50px;
  border: 1px solid #black;
}
</style>
</head>
<body>

<h2>CSS Padding</h2>
<div>This element has a padding of 70px.</div>

</body>
</html>

Output:

Padding – Shorthand Property

In order to shorten the code, it is feasible to define all the padding properties in one property.

The paddingproperty is a shorthand property for the subsequent individual padding properties:

  • padding-top
  • padding-right
  • padding-bottom
  • padding-left

So, here is how it works:

If the padding property has four values:

padding: 100px 70px 50px 25px;

  • top padding is 100px
  • right padding is 75px
  • bottom padding is 50px
  • left padding is 25px

Using the padding shorthand

The usage of those is very simple and cannot be confused, for example:

1 value

Utilizing a single value implements that to all the paddings: top, right, bottom, left.

padding: 20px;

2 values

Working 2 values utilizes the first to bottom & top, and the second to left & right.

padding: 20px 10px;

3 values

Using 3 values practices the first to top, the second to left & right, the third to bottom.

padding: 20px 10px 30px;

4 values

Using 4 values applies the first to top, the second to the right, the third to bottom, the fourth to left.

padding: 20px 10px 5px 0px;
Categories CSS

The CSS Fonts Tutorial | Complete Guide on CSS Font with Example Programs

The CSS Fonts Tutorial

Picking up the right font for your website is important! It leads to the design of attractive web pages and engaging platforms for users. Want to learn more about fonts in CSS? Then, click on the below links and make use of the details clearly while programming in CSS language.

CSS Font Property

The CSS font property allows you to utilize various font properties in a single one, reducing the clutter. Below are some of the CSS fontproperty attributes:

  • CSS Font color: This property is used to change the color of the text. (standalone attribute)
  • CSS Font family: This property is used to change the face of the font.
  • CSS Font size: This property is used to increase or decrease the size of the font.
  • CSS Font style: This property is used to make the font bold, italic, or oblique.
  • CSS Font variant: This property creates a small-caps effect.
  • CSS Font weight: This property is used to increase or decrease the boldness and lightness of the font.

Example on CSS Font

Use font to set several font properties in one declaration:

.a {
  font: 20px Arial, sans-serif;
}
.b {
  font: italic small-caps bold 30px serif;
}

Do Check: 

Why Font Selection is Important?

Selecting the right font has a huge impact on how the readers experience a website.

The right font can create a strong identity for your brand.

Using a font that is easy to read is important. The font adds value to your text. It is also important to choose the correct color and text size for the font.

Font Families

In CSS these are the most used generic font families:

  1. Serif fonts have a small stroke at the edges of each letter. They create a sense of formality and elegance.
  2. Sans-serif fonts have clean lines (no small strokes attached). They create a modern and minimalistic look.
  3. Monospace fonts – here all the letters have the same fixed width. They create a mechanical look.
  4. Cursive fonts imitate human handwriting.

Note: On computer screens, sans-serif fonts are considered easier to read than serif fonts.

Difference Between Serif and Sans-serif Fonts

Difference Between Serif and Sans-serif Fonts

Example

.p1 {
  font-family: "Times New Roman", Times, serif;
}

.p2 {
  font-family: Arial, Helvetica, sans-serif;
}

.p3 {
  font-family: "Lucida Console", "Courier New", monospace;
}

Font-Weight

This property sets the width of a font. You can use those predefined values:

  • normal
  • bold
  • bolder (relative to the parent element)
  • lighter (relative to the parent element)

Example:

p.normal {
  font-weight: normal;
}

p.thick {
  font-weight: bold;
}

p.thicker {
  font-weight: 900;
}

Or using the numeric keywords

  • 100
  • 200
  • 300
  • 400, mapped to normal
  • 500
  • 600
  • 700 mapped to bold
  • 800
  • 900

where 100 is the lightest font, and 900 is the boldest.

Font-Stretch

The font-stretchproperty allows you to make text narrower (condensed) or wider (expanded).

Note: This property has no effect if the selected font does not offer condensed or expanded faces!

Value Description
ultra-condensed Makes the text as narrow as it gets
extra-condensed Makes the text narrower than condensed, but not as narrow as ultra-condensed
condensed Makes the text narrower than semi-condensed, but not as narrow as extra-condensed
semi-condensed Makes the text narrower than normal, but not as narrow as condensed
normal Default value. No font stretching
semi-expanded Makes the text wider than normal, but not as wide as expanded
expanded Makes the text wider than semi-expanded, but not as wide as extra-expanded
extra-expanded Makes the text wider than expanded, but not as wide as ultra-expanded
ultra-expanded Makes the text as wide as it gets
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Syntax

font-stretch: normal | semi-condensed | condensed | extra-condensed | ultra-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded

Example:

Example
<!DOCTYPE html>  
<html>  
<head>  
<title>  
CSS font-stretch Property  
</title>  
  
<style>  
body{  
text-align: center;  
}  
div{  
font-family: Arial, Helvetica, sans-serif;  
font-size: 20px;  
color: blue;  
}  
.normal {  
font-stretch: normal;  
}  
.semi-condensed {  
font-stretch: semi-condensed;  
}  
.condensed {  
font-stretch: condensed;  
}  
.extra-condensed {  
font-stretch: extra-condensed;  
}  
.ultra-condensed {  
font-stretch: ultra-condensed;  
}  
  
.semi-expanded {  
font-stretch: semi-expanded;  
}  
  
.expanded {  
font-stretch: expanded;  
}  
.extra-expanded {  
font-stretch: extra-expanded;  
}  
  
.ultra-expanded {  
font-stretch: ultra-expanded;  
}  
</style>  
</head>  
  
<body>  
<h1> Example of the font-stretch property </h1>  
<div class = "normal">  
normal  
</div>  
  
<div class = "semi-condensed">  
semi-condensed  
</div>  
<div class = "condensed">  
condensed  
</div>  
  
<div class = "extra-condensed">  
extra-condensed  
</div>  
  
<div class = "ultra-condensed">  
ultra-condensed  
</div>  
<div class = "semi-expanded">  
semi-expanded  
</div>  
  
<div class = "expanded">  
expanded  
</div>  
  
<div class = "extra-expanded">  
extra-expanded  
</div>  
  
<div class = "ultra-expanded">  
ultra-expanded  
</div>  
</body>  
  
</html>

Output:

CSS font-stretch property example output

Font-Size

This property is used to determine the size of the fonts.

Font Size Value Description
xx-small used to display the extremely small text size.
x-small used to display the extra small text size.
small used to display small text size.
medium used to display medium text size.
large used to display large text size.
x-large used to display extra large text size.
xx-large used to display extremely large text size.
smaller used to display comparatively smaller text size.
larger used to display comparatively larger text size.
size in pixels or % used to set value in percentage or in pixels.

Example:

.a {
  font-size: 15px;
}

.b {
  font-size: large;
}

.c {
  font-size: 150%;
}
Categories CSS

The CSS float property and clearing | CSS Floating Property & CSS Clear Property with Examples

The CSS float property and clearing

This tutorial helps you to understand and learn what is CSS float property and CSS clear property with Example programs. The CSS floatproperty defines how an element should float. The CSS clearproperty defines what elements can float beside the cleared element and on which side. Also, collect more information from the direct links available below:

The FLOAT Property

The float property is used for positioning and formatting content e.g. let an image float left to the text in a container.

The float property can have one of the following values:

  • left – The element floats to the left of its container
  • right – The element floats to the right of its container
  • none – The element does not float (will be displayed just where it occurs in the text). This is default
  • inherit – The element inherits the float value of its parent

In its simplest use, thefloatproperty can be used to wrap text around images.

Also Check: 

FLOAT RIGHT Syntax:

img {
  float: right;
}

Example Code (using inline styling)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <img
      src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1200px-Image_created_with_a_mobile_phone.png"
      alt=""
      style="float: right; height: 20%; width: 20%"
    />
    <p style="font-size: 20px">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus
      imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae
      scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec
      congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet.
      Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent
      convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis
      dictum nisi, sed ullamcorper ipsum dignissim
    </p>
  </body>
</html>

So the output would be :

FLOAT LEFT Syntax:

img{
 float:left;
}

Example program (using inline styling)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="style.css" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <img
      src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1200px-Image_created_with_a_mobile_phone.png"
      alt=""
      style="float: left; height: 20%; width: 20%"
    />
    <p style="font-size: 20px">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus
      imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae
      scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec
      congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet.
      Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent
      convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis
      dictum nisi, sed ullamcorper ipsum dignissim
    </p>
  </body>
</html>

Output:

Example – Float Next To Each Other

Usually, div elements will be presented on top of each other. But, if we use float: left we can let elements float next to each other. So, check out the below program

div {
  float: left;
  padding: 15px;
}

.div1 {
  background: red;
}

.div2 {
  background: yellow;
}

.div3 {
  background: green;
}

The CLEAR Property

The clearproperty specifies what elements can float beside the cleared element and on which side.

The clearproperty can have one of the following values:

  • none – Allows floating elements on both sides. This is default
  • left – No floating elements allowed on the left side
  • right- No floating elements allowed on the right side
  • both – No floating elements allowed on either the left or the right side
  • inherit – The element inherits the clear value of its parent

The most common way to use the clear property is after you have used a float property on an element.

The following example clears the float to the left. This means that no floating elements are allowed on the left side (of the div):

<!DOCTYPE html>
<html>
  <head>
    <style>
      div {
        border: 3px solid #4caf50;
        padding: 5px;
      }

      .img1 {
        float: right;
      }

      .clearfix {
        overflow: auto;
      }

      .img2 {
        float: right;
      }
    </style>
  </head>
  <body>
    <h2>Clearfix</h2>

    <p>
      In this example, the image is taller than the element containing it, and
      it is floated, so it overflows outside of its container:
    </p>

    <div>
      <img
        class="img1"
        src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1200px-Image_created_with_a_mobile_phone.png"
        alt="Pineapple"
        width="170"
        height="170"
      />
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus
      imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae
      scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec
      congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet.
      Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent
      convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis
      dictum nisi, sed ullamcorper ipsum dignissim
    </div>

    <p style="clear: right">
      Add a clearfix class with overflow: auto; to the containing element, to
      fix this problem:
    </p>

    <div class="clearfix">
      <img
        class="img2"
        src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1200px-Image_created_with_a_mobile_phone.png"
        alt="Pineapple"
        width="170"
        height="170"
      />
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus
      imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae
      scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec
      congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet.
      Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent
      convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis
      dictum nisi, sed ullamcorper ipsum dignissim
    </div>
  </body>
</html>
.clearfix {
  overflow: auto;
}

Output image(s), after floating them, explained with margins.

Techniques for Clearing Floats

Below are some of the useful & helpful clearing floats techniques that we need typically at sometimes:

  • The Empty Div Method
  • The Overflow Method
  • The Easy Clearing Method
Categories CSS

CSS Normalizing | Definition, Installation, How to Use it & Difference Between Normalize CSS & Reset CSS

CSS Normalizing

Normalize.css is a small CSS file that provides better cross-browser consistency in the default styling of HTML elements. It’s a modern, HTML5-ready, alternative to the traditional CSS reset. Currently, Normalize.css is used in some form by Twitter Bootstrap, HTML5 Boilerplate, GOV.UK, Rdio, CSS Tricks, and many other frameworks, toolkits, and sites.

In this tutorial, we have shared the complete information about what is CSS Normalizing, how to use it, and Normalize vs Reset CSS.

CSS Normalizing

Normalize.css is a substitute for CSS resets. The project is the product of 100’s of hours of great research by @necolas and @jon_neal. They intended to:

  • Preserve useful browser defaults rather than erasing them.
  • Improve usability with subtle improvements.
  • Normalize styles for a wide range of HTML elements.
  • Explain the code using comments and detailed documentation.
  • Correct bugs and common browser inconsistencies.

It supports a wide range of browsers (including mobile browsers) and includes CSS that normalizes HTML5 elements, typography, lists, embedded content, forms, and tables.

Despite the project being based on the principle of normalization, it uses pragmatic defaults where they are preferable.

The below-written code comes with the library itself:

html {
  line-height: 1.15; /* 1 */
  -webkit-text-size-adjust: 100%; /* 2 */
}

/* Sections
   ========================================================================== */

/**
 * Remove the margin in all browsers.
 */

body {
  margin: 0;
}

/**
 * Render the `main` element consistently in IE.
 */

main {
  display: block;
}

/**
 * Correct the font size and margin on `h1` elements within `section` and
 * `article` contexts in Chrome, Firefox, and Safari.
 */

h1 {
  font-size: 2em;
  margin: 0.67em 0;
}

/* Grouping content
   ========================================================================== */

/**
 * 1. Add the correct box sizing in Firefox.
 * 2. Show the overflow in Edge and IE.
 */

hr {
  box-sizing: content-box; /* 1 */
  height: 0; /* 1 */
  overflow: visible; /* 2 */
}

/**
 * 1. Correct the inheritance and scaling of font size in all browsers.
 * 2. Correct the odd `em` font sizing in all browsers.
 */

pre {
  font-family: monospace, monospace; /* 1 */
  font-size: 1em; /* 2 */
}

/* Text-level semantics
   ========================================================================== */

/**
 * Remove the gray background on active links in IE 10.
 */

a {
  background-color: transparent;
}

/**
 * 1. Remove the bottom border in Chrome 57-
 * 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.
 */

abbr[title] {
  border-bottom: none; /* 1 */
  text-decoration: underline; /* 2 */
  text-decoration: underline dotted; /* 2 */
}

/**
 * Add the correct font weight in Chrome, Edge, and Safari.
 */

b,
strong {
  font-weight: bolder;
}

/**
 * 1. Correct the inheritance and scaling of font size in all browsers.
 * 2. Correct the odd `em` font sizing in all browsers.
 */

code,
kbd,
samp {
  font-family: monospace, monospace; /* 1 */
  font-size: 1em; /* 2 */
}

/**
 * Add the correct font size in all browsers.
 */

small {
  font-size: 80%;
}

/**
 * Prevent `sub` and `sup` elements from affecting the line height in
 * all browsers.
 */

sub,
sup {
  font-size: 75%;
  line-height: 0;
  position: relative;
  vertical-align: baseline;
}

sub {
  bottom: -0.25em;
}

sup {
  top: -0.5em;
}

/* Embedded content
   ========================================================================== */

/**
 * Remove the border on images inside links in IE 10.
 */

img {
  border-style: none;
}

/* Forms
   ========================================================================== */

/**
 * 1. Change the font styles in all browsers.
 * 2. Remove the margin in Firefox and Safari.
 */

button,
input,
optgroup,
select,
textarea {
  font-family: inherit; /* 1 */
  font-size: 100%; /* 1 */
  line-height: 1.15; /* 1 */
  margin: 0; /* 2 */
}

/**
 * Show the overflow in IE.
 * 1. Show the overflow in Edge.
 */

button,
input { /* 1 */
  overflow: visible;
}

/**
 * Remove the inheritance of text transform in Edge, Firefox, and IE.
 * 1. Remove the inheritance of text transform in Firefox.
 */

button,
select { /* 1 */
  text-transform: none;
}

/**
 * Correct the inability to style clickable types in iOS and Safari.
 */

button,
[type="button"],
[type="reset"],
[type="submit"] {
  -webkit-appearance: button;
}

/**
 * Remove the inner border and padding in Firefox.
 */

button::-moz-focus-inner,
[type="button"]::-moz-focus-inner,
[type="reset"]::-moz-focus-inner,
[type="submit"]::-moz-focus-inner {
  border-style: none;
  padding: 0;
}

/**
 * Restore the focus styles unset by the previous rule.
 */

button:-moz-focusring,
[type="button"]:-moz-focusring,
[type="reset"]:-moz-focusring,
[type="submit"]:-moz-focusring {
  outline: 1px dotted ButtonText;
}

/**
 * Correct the padding in Firefox.
 */

fieldset {
  padding: 0.35em 0.75em 0.625em;
}

/**
 * 1. Correct the text wrapping in Edge and IE.
 * 2. Correct the color inheritance from `fieldset` elements in IE.
 * 3. Remove the padding so developers are not caught out when they zero out
 *    `fieldset` elements in all browsers.
 */

legend {
  box-sizing: border-box; /* 1 */
  color: inherit; /* 2 */
  display: table; /* 1 */
  max-width: 100%; /* 1 */
  padding: 0; /* 3 */
  white-space: normal; /* 1 */
}

/**
 * Add the correct vertical alignment in Chrome, Firefox, and Opera.
 */

progress {
  vertical-align: baseline;
}

/**
 * Remove the default vertical scrollbar in IE 10+.
 */

textarea {
  overflow: auto;
}

/**
 * 1. Add the correct box sizing in IE 10.
 * 2. Remove the padding in IE 10.
 */

[type="checkbox"],
[type="radio"] {
  box-sizing: border-box; /* 1 */
  padding: 0; /* 2 */
}

/**
 * Correct the cursor style of increment and decrement buttons in Chrome.
 */

[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
  height: auto;
}

/**
 * 1. Correct the odd appearance in Chrome and Safari.
 * 2. Correct the outline style in Safari.
 */

[type="search"] {
  -webkit-appearance: textfield; /* 1 */
  outline-offset: -2px; /* 2 */
}

/**
 * Remove the inner padding in Chrome and Safari on macOS.
 */

[type="search"]::-webkit-search-decoration {
  -webkit-appearance: none;
}

/**
 * 1. Correct the inability to style clickable types in iOS and Safari.
 * 2. Change font properties to `inherit` in Safari.
 */

::-webkit-file-upload-button {
  -webkit-appearance: button; /* 1 */
  font: inherit; /* 2 */
}

/* Interactive
   ========================================================================== */

/*
 * Add the correct display in Edge, IE 10+, and Firefox.
 */

details {
  display: block;
}

/*
 * Add the correct display in all browsers.
 */

summary {
  display: list-item;
}

/* Misc
   ========================================================================== */

/**
 * Add the correct display in IE 10+.
 */

template {
  display: none;
}

/**
 * Add the correct display in IE 10.
 */

[hidden] {
  display: none;
}

How to use normalize.css?

First and foremost, install or download normalize.css from GitHub. After that, there are two main approaches to use it.

Method 1: make use of normalize.css as a starting point for your own project’s base CSS, customizing the values to meet the design’s requirements.

Method 2: insert normalize.css untouched and build upon it, overriding the defaults later in your CSS if required.

Installation of Normalise CSS

  • For node package manager, use the following in a terminal npm install normalise.css
  • For yarn packages, yarn normalise.css  use the following in a terminal

Difference Between Normalize.css and Reset CSS

Here are some of the differences between Normalize.css and Reset CSS. Have a look at the below points:

Normalize.css corrects common bugs

It fixes common desktop and mobile browser bugs that are out of scope for resets.

This includes display settings for HTML5 elements, correctingfont-sizefor preformatted text, SVG overflow in IE9, and many form-related bugs across browsers and operating systems.

Normalize.css doesn’t clutter your debugging tools

A common irritation when using resets is the large inheritance chain that is displayed in browser CSS debugging tools.

Normalize.css is modular

The project is broken down into relatively independent sections, making it easy for you to see exactly which elements need specific styles. Furthermore, it gives you the potential to remove sections if you know they will never be needed by your website.

Normalize.css has extensive documentation

This means that you can find out what each line of code is doing, why it was included, what the differences are between browsers, and more easily run your own tests.

The project aims to help educate people on how browsers render elements by default and make it easier for them to be involved in submitting improvements.

Categories CSS

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 put an item at the bottom of its container using CSS | CSS bottom & position Property

How to put an item at the bottom of its container using CSS

CSS permits us to align the content of an <div> element to the bottom with appropriate methods. Furthermore, we can align the content to the bottom on the left or on the right side or at possible variants. In this tutorial, we’ll discuss completely How to put an item at the bottom of its container using CSS with Example program. Let’s stick to this page and learn quickly.

CSS bottom Property

The bottom CSS property participates in setting the vertical position of a positioned element. It does not affect non-positioned elements.

  • In case the position is absolute or fixed then the bottom property sets the bottom edge of an element to a unit above/below the bottom edge of its nearest positioned ancestor.
  • If the position: relative then the bottom property addresses the element’s bottom edge to move above/below its normal position.
  • In case of the position: sticky then the bottom property acts like its position is near when the element is inside the viewport, and like its position is fixed when it is outside.
  • If the position: static then the bottom property has no effect.

Sample Code:

div.absolute {
  position: absolute;
  bottom: 10px;
  width: 50%;
  border: 3px solid #8AC007;
}

Basic Property of CSS:

  • position: The position property defines the type of positioning method utilized for an element. For instance: static, relative, absolute, and fixed.
  • bottom: The bottom property affects the vertical position of a positioned element. This property does not affect non-positioned elements.
  • left: The left property affects the horizontal position of a positioned element. This property does not affect non-positioned elements.
  • right: The right property affects the horizontal position of a positioned element. This property does not affect non-positioned elements.

Also Check: What are good CSS Breakpoint values for Responsive Design?

How to position a div at the bottom of its container using CSS?

It’s a rather common thing to do, and I had to do it recently.

I was blindly assigningbottom: 0 to an element that I wanted to stick to the bottom of its parent.

Turns out I was forgetting 2 things: settingposition: absoluteon that element and addingposition: relativeon the parent.

Position attribute uses multiple values which are noted below:

  • absolute: This property is applied when the position of a division is relative to its parent.
  • relative: This property is utilized when the position of a division is relative to other elements on the screen.
  • fixed: This property is used when the position of a component to be fixed on-screen irrespective of other HTML parts (like a footer note).

The position property along with attributes like left, right, top and bottom, can be utilized to perform relevant positioning.

Example:

<div class="container-element">
  ...
  <div class="element-to-stick-to-bottom">
    ...
  </div>
</div>
.element-to-stick-to-bottom {
  position: absolute;
  bottom: 0;
}

.container-element {
  position: relative;
}

Example on How to put an item at the bottom of its container using CSS

By using the CSS position Property, You can easily align the content of a DIV to the bottom. Let’s have a look at the below code for understanding how it actually works:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>CSS Align Content of a Div to the Bottom</title>
<style>
    .box{
        color: #fff;
        background: #000;
        position: relative;
        min-height: 200px;
        padding-bottom: 30px; /* to avoid content overlapping */
    }
    .box .content{    
        position: absolute;
        bottom: 0;
        left: 0;
    }
</style>
</head>
<body>
    <div class="box">
        <h1>Page Title</h1>
        <div class="content">This piece of text will remain at the bottom of the parent div all the time.</div>
    </div>
</body>
</html>

Result:

CSS div alignment output

Categories CSS

What are good CSS Breakpoint values for Responsive Design? | What is CSS Breakpoint? & How to set them?

What are good CSS Breakpoint values for Responsive Design

Get started learning CSS breakpoints, and want to become a mobile website master! Then, having knowledge of CSS Breakpoints and how to use them is very important. Also, you can learn exactly What are good CSS Breakpoint values for Responsive Design? from this tutorial. So, continue your read by taking the help of these direct links.

What is a CSS breakpoint?

The points where the website content responds in accordance with the device width, enabling you to show the best possible layout to the user are called CSS breakpoints.

CSS breakpoints are also known as media query breakpoints, as they are utilized with a media query.

In the below instance, you can observe how the layout changes to the screen size. The layout at large resolution has a header and two-column body layout but in a small device, it turns into one column layout.

css breakpoints image

Also Check:

How to set CSS Breakpoints to create Responsive Designs?

The complicated part is to choose the breakpoints themselves. There aren’t any standard templates, and many frameworks use distinct breakpoints.

So, it’s time to know what approach need you to adopt for your breakpoints?

Here, there are two feasible approaches to follow:

  • Breakpoints based on device
  • Breakpoints based on content

Breakpoints based on device

Choosing breakpoints on the basis of various devices sounds like a good idea, but in reality, it’s not constantly the most suitable approach. We already have sufficient devices to worry about, and when a new one comes out with another width, going back to your CSS and adding a new breakpoint all over again is time-consuming.

But, it’s still a viable option, as you may discover that runs okay for you. Also, with this strategy, you will end up becoming a huge list of media queries.

Here’s an instance of device-specific breakpoints:

/* ----------- iPhone 6, 6S, 7 and 8 ----------- */
 
/* Portrait */
 
@media only screen
 
and (min-device-width: 375px)
 
and (max-device-width: 667px)
 
and (-webkit-min-device-pixel-ratio: 2)
 
and (orientation: portrait) {
 
}
 
/* Landscape */
 
@media only screen
 
and (min-device-width: 375px)
 
and (max-device-width: 667px)
 
and (-webkit-min-device-pixel-ratio: 2)
 
and (orientation: landscape) {
 
}
 
/* ----------- Google Pixel ----------- */
 
/* Portrait */
 
@media screen
 
and (device-width: 360px)
 
and (device-height: 640px)
 
and (-webkit-device-pixel-ratio: 3)
 
and (orientation: portrait) {
 
}
 
/* Landscape */
 
@media screen
 
and (device-width: 360px)
 
and (device-height: 640px)
 
and (-webkit-device-pixel-ratio: 3)
 
and (orientation: landscape) {
 
}

Breakpoints based on content

The absolute option for deciding breakpoints is based on the content of your site. This method allows you to just add breakpoints where your content requires layout improvement. This will give your media query a lot easier and manageable.

This CSS breakpoint will apply when the device width is 768px and above.

@media only screen (min-width: 768px){
 
...
 
}

Also, you can set a range with breakpoints, so the CSS will only apply within those limits.

@media only screen and (min-width: 768px) and (max-width: 959px){
 
...
 
}

What are good CSS Breakpoint values for Responsive Design?

The optimal CSS breakpoint values we should use in our projects. Personal preferences.

While designing a site, I noticed I was using some pretty random values for my CSS breakpoints. Sometimes a rounded value like 800 or 1200, sometimes a specific value up to the pixel like 672.

I searched for the proper values to apply to my breakpoints going forward.

I had a little bit of time to look this up, and I came to this conclusion.

We have 5 major device sizes to worry about:

  • mobile portrait
  • mobile landscape
  • tablet portrait
  • tablet landscape
  • laptop

Those devices map to those pixel values:

  • mobile portrait: less than 640px
  • mobile landscape: > 640px
  • tablet portrait: > 768px
  • tablet landscape: > 1024px
  • laptop: > 1280px

This means my CSS, without any media query, is going to design for the mobile portrait use case, and then adding breakpoints I’ll design for devices that are bigger and bigger, banning the max-width from media queries.

I think I always went for the opposite route: a design for bigger screens, which is what I use the most, and then go smaller, but designing mobile-first and using min-width seems the most accepted and used solution nowadays.

These are the media queries I will use from now on:

@media (min-width: 640px) {

}

@media (min-width: 768px) {

}

@media (min-width: 1024px) {

}

@media (min-width: 1280px) {

}
Categories CSS

How to align center in flexbox | Properties To Align Text in CSS Flexbox

How to align center in flexbox

The most important reason that flexbox immediately caught the attention of web developers is that it took proper alignment skills to the web for the first time. It allowed proper vertical alignment, so everyone can ultimately easily center a box. In this tutorial, we will take a thorough look at how the alignment and justification properties work and align center in Flexbox.

Properties that control alignment

The properties that are used to control alignment are as follows:

  • justify-content — controls the alignment of all items on the main axis.
  • align-items — controls the alignment of all items on the cross axis.
  • align-self — controls alignment of an individual flex item on the cross axis.
  • align-content — described in the spec as for “packing flex lines”; controls space between flex lines on the cross axis.

How to Center Text in CSS Using text-align?

If you want to utilize CSS to the center text within an element such as a div, header, or paragraph, then you can use the CSS text-align property.

Fixing the text-align property to the center is the most popular method to horizontally align text by CSS. This method is not limited to just text, it can be applied to center most child elements that are smaller than the container element.

There are three things that must be commenced for text-align to properly horizontally center text and child elements.

  • The text or target element needs to be covered or contained by a parent (wider of course) element.
  • The parent element’s text-align CSS property should be set to ‘center’.
  • In case you are centering an element its display property should be ‘inline-block’.

If you hold various child elements they will collectively center within the parent element. Also, text-align has multiple valid properties:

  • center: text is centered
  • left: text is aligned to the container’s left side
  • right: text is aligned to the container’s right side
  • justify: text is forced to line up with the container’s left and right edges, except for the last line
  • justify-all: forces the last line to justify it’s text
  • start: same as left if language text direction is left to right. But right if the language text direction is right to left.
  • end: the opposite of start
  • match-parent: similar to inherit, except start and end are calculated with respect to the parent element

Make use of the above properties to align text within the parent or wrapper div.

Also Refer: How to make a collapsible menu using only CSS

How to Align Center in Flexbox?

Flexbox has become my favorite way to center an element on a page.

You wrap an item in adiv, and you set display: flex and justify-content: center.

<div class="wrapper"> ... </div>
.wrapper {
  display: flex;
  justify-content: center;
}

Using Tailwind CSS it’s easier, all you have to do is to add the flex and justify-center classes:

<div class="flex justify-center">
   ...
</div>
Categories CSS

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