Positions in CSS and Media Queries

Positions in CSS and Media Queries

Position

It describes the position of an element in an HTML document.

We have five different ways to declare positions :

    position: absolute;
    position: relative;
    position: fixed;
    position: sticky;
    position: static;

absolute

absolute set its position according to its parent element, and it did not hold its old space.

relative

relative sets its position according to its current position, and it also holds its old space.

fixed

position fixed used to set an element in a fixed position that it cannot move and it did not hold its old space.

sticky

position sticky is used to fix a position and whenever an HTML document is scrolled it sticks on top.

static

position static is the default value of the position.

the top, right, left, and bottom has no effect on position: static;

Media Queries

Media Queries allow you to apply CSS property according to display size, orientation, or screen resolution.

Media queries are used to target general (such as print vs. screen) or devices like phones, tablets, and laptops and to make responsive of any website.

Example :

If the browser window is 600px or smaller, the background color will be light-blue:

@media only screen and (max-width: 600px) {
  body {
    background-color: lightblue;
  }
}

Breakpoints

We can add as many breakpoints as we want but here are some specific breakpoints for specific devices

Extra small devices (phones, 600px and down)

@media only screen and (max-width: 600px) {
    ...
}

Small devices (portrait tables and large phones, 600px and up)

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

Medium devices (landscape tablets, 768px and up)

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

Large devices (laptops/desktops, 992px and up)

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

Extra large devices (large laptops and desktops, 1200px and up)

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

Orientation: Portrait / Landscape

The web page will have a lightblue background if the orientation is in landscape mode:

@media only screen and (orientation: landscape) {
  body {
    background-color: lightblue;
  }
}

we can apply all the CSS properties in media queries whether it be for hiding elements or changing font size.