How to use @media for responsive design in websites

@media is a CSS3 module allowing content rendering to adapt to conditions such as screen size, device-orientation or display-density. A media query consists of a media type and one or more expressions.

It allows a web page to display differently on different devices and browser sizes.

Consider the example


/*For Desktops*/
@media(min-width: 768px){
	p{
	font-family: Arial;
	font-size: 20px;
	text-align: left;
	padding: 28px 80px;
	}
}

The above code is used to display a paragraph with font size ’20px’ and padding ’28px'(top and bottom padding) ’80px'(left and right padding) on desktops.The code works for devices with width > 768px.

If we want different font size and padding for mobile devices use the below code.

/*For Mobile devices*/
@media(max-width: 767px){
	p{
	font-family: Arial;
	font-size: 15px;
	text-align: left;
	padding: 14px 40px;
	}
}

The above code is used to display a paragraph with font size 15px and padding ’14px'(top and bottom padding) 40px(left and right padding) on desktops. So the paragraph will look smaller on mobile devices. The code works for devices with width < 768px.

Put the both code variations in a single css file. Eg paragraph.css


/*For Desktops*/
@media(min-width: 768px){
	p{
	font-family: Arial;
	font-size: 20px;
	text-align: left;
	padding: 28px 80px;
	}
}

/*For Mobile devices*/
@media(max-width: 767px){
	p{
	font-family: Arial;
	font-size: 15px;
	text-align: left;
	padding: 14px 40px;
	}
}