CSS Units in a nutshell π
Are you still writing your css units in pixels and percentages? if you are then I would recommend you check out this article where we will cover all possible CSS units with example and its details of use cases.
There are two types of length units:Β absoluteΒ andΒ relative. 1 to 6 in the list are absolute units while the remaining ones are relative to other elements in the DOM
List of Units
Pixels
Pixels are the most commonly used way to assign length in css. A pixel represents the smallest possible unit of the screen.
a minute area of illumination on a display screen, one of many from which an image is composed.
/* Used for defining absolute values */
h1{
padding:10px;
}
Inches
1 Inch = 96px = 2.54cm
Inch is not so commonly used but it has the same behaviour as px just a different unit of measurement.
/* Used for defining absolute values */
h1{
padding:10in;
}
Milimeters
/* Used for defining absolute values */
h1{
padding:10mm;
}
Centimeters
/* Used for defining absolute values */
h1{
padding:5cm;
}
Points | 1pt = 1/72 of 1in
/* Used for defining absolute values */
h1{
padding:10pt;
}
picas | 1pc = 12pt
/* Used for defining absolute values */
h1{
padding:10pc;
}
Percentage
/* Sizes the child on the basis of its parents parent element's length. */
img{
max-width:100%;
}
em
/* Relative to the font size of the current element */
/* if font size is 16px then 1em = 16px and 2em = 32px */
h1{
padding:10em;
}
rem
/* Relative to the font size of the root element */
/* if font size is 16px then 1rem = 16px and 2em = 32px */
:root{
font-size:35px
}
h1{
padding:3rem;
/* This will be equal to 3*35 = 105px */
}
ch
/* Relative to the width of the a character "_" */
h1{
padding:1ch;
}
vh : View Height
/* Relative to the height of the window */
section{
min-height:70vh;
/* covers 70% of the screen height */
}
vw : View Width
/* Relative to the width of the window */
section{
max-width:90vw;
margin:0 auto;
}
vmin : Minimum width out of vw and vh
/* Used for selecting Minimum width out of vw and vh */
h1{
padding:5vmin;
}
vmax : Maximum width out of vw and vh
/* Used for selecting Maximum width out of vw and vh */
h1{
padding:5vmax;
}
ex: x-height of current font
/* Relative to x-height of current font */
h1{
padding:10ex;
}
fr: Frames used in grid
/* Used for defining absolute values */
section{
display:grid;
grid-template-columns:1fr 1fr;
/* creates a 2 col layout */
}
I hope you learned something new today if you did then please share this post with your friends who might find this useful aswell. Have any questions? Feel free to connect with me on LinkedIn Twitter @singhkunal2050. You can also write me here.
Happy Coding π©βπ»!