How to make content responsive with CSS
Responsive design is an essential aspect of web development as it helps to create web content that can adjust to various screen sizes on different devices. CSS plays a vital role in creating responsive web design, and it can be used to make HTML content responsive with ease.
Syntax
@media (max-width: 600px) { .class-name { property:value; } }
The above CSS syntax is used to define media queries that target screen widths that are less than or equal to 600 pixels. When the screen width is 600px or less, the styles defined within the curly brackets will be applied to the HTML element with the class name “.class-name”.
Usage Examples
1. Responsive Images
Images are a crucial part of websites, and they need to be responsive so that they can adjust to different screen sizes. One way to make images responsive is to use the “max-width” property in CSS.
img { max-width: 100%; height: auto; }
The above CSS code ensures that the image can not exceed its parent container’s width and adjust its height accordingly.
2. Responsive Typography
Typography is a crucial part of web design, and it needs to be readable on different screen sizes. Here’s an example of responsive typography that adjusts its font-size depending on the screen size.
@media (max-width: 600px) { h1 { font-size: 2rem; } } @media (min-width: 601px) and (max-width: 1200px) { h1 { font-size: 2.5rem; } } @media (min-width: 1201px) { h1 { font-size: 4rem; } }
In the above code, we define three media queries that target different screen sizes. The font-size for the “h1” element is adjusted accordingly to ensure that it is readable on different screen sizes.
3. Responsive Navigation Menu
The navigation menu is an essential part of a website, and it needs to be easily accessible on different screen sizes. Here’s an example of responsive navigation that turns into a burger menu or a dropdown on smaller screen sizes.
nav { display: flex; justify-content: space-between; align-items: center; height: 80px; } nav ul { display: flex; list-style: none; } nav ul li { margin-right: 20px; } @media (max-width: 600px) { nav { flex-wrap: wrap; height: auto; } nav ul { width: 100%; justify-content: center; margin: 0; } nav ul li { margin-bottom: 10px; } .burger { display: block; } } .burger { display: none; }
The above CSS code defines a media query with a maximum screen width of 600px, where the navigation menu turns into a burger menu. The hamburger menu icon’s code is in the HTML code, and it is hidden until the media query is activated, where it becomes visible, replacing the original navigation menu.
Additional Resources
Here is an external resource on responsive web design that guides you on how to create responsive websites from scratch:
https://www.w3schools.com/Css/css_rwd_intro.asp
Written by: Michael from Beginnrtuts.com 26-05-2023 Written in: CSS tutorials