How To Give Your Desktop Site Mobile Styling
@media screen and (max-width: 480px){}
I am currently building a website and wanted it to be accessible on both computers and mobile devices. I researched a bunch of different solutions that involved emulators and other additional downloads but eventually found out that this can be done using only CSS!
Before we get to any code, it’s important to realize how “CSS” works as its core. CSS stands for “Cascading Style Sheets” and because they are cascading, the order that the code is in your file matters. If you have two of the same CSS properties, the one on the bottom will be the one that is executed.
.content {
text-align: center;
text-align: left;
}
This code will result in the code being aligned to the left.
When I am doing mobile styling, I like to keep the CSS for the web and mobile in two separate files to make everything more readable. It is crucial that when you are doing your mobile styling, you import the mobile CSS file below the web CSS file because if you put it above, the web file attributes will overwrite the mobile. I’ll explain this more in a bit!
In order to see what your site will look like on a mobile device, open your developer tools (right click, inspect), then click on the “Toggle device toolbar” button next to the element selector. You can then choose which device you want to view the site on.
Right now, I have some very basic CSS properties in my web CSS file centering the heading, and making the paragraphs take up 75% of the view width. Using “vw” and “vh” to adjust the view width and height is extremely helpful when it comes to making your site responsive.
.content h1 {
text-align: center;
}.content p {
width: 75vw;
margin: auto;
}
Now my mobile CSS file, I am going to add some code that will affect the page only when the width of the screen is under 480px. Then, I am going to make the header aligned to the left. You can change “480px” to whatever you want, but I have found this works best for most mobile devices.
@media screen and (max-width: 480px) {
.content h1 {
text-align: left;
}
}
Check out the results in both the web version, and the mobile version.
As you can see, the web version still has the text centered, but the mobile version has it aligned to the left.
I mentioned before that your mobile styling needs to come after your web styling so that it is not overwritten. I am currently importing my CSS files as such:
import "../../css/web/Blog.css"
import "../../css/mobile/BlogMobile.css"
If I flip them around…
import "../../css/mobile/BlogMobile.css"
import "../../css/web/Blog.css"
…the title is now centered again. This is because our code is currently saying, “if the screen width is less than 480px, put the title on the left. Then, center all titles.” The CSS attribute on the bottom is the one that takes affect!
You can use this method to create specific CSS for any screen size! Remember to use “vw”, “vh”, and percentages to style to make it easy on yourself!