Media Queries in CSS

Learn how to make your website responsive on desktops, tablets, and mobile phones, using media queries in CSS.

What are media queries ?

In CSS, media queries are used to apply styles on your website based on the properties of the user’s device. It helps you make your website responsive on all devices (desktops, tablets, and mobile phones).

Video Tutorial

If you prefer following a video tutorial, here you are:

We will be using a grid column. So let’s say you have a row container with 12 columns in it.

<div class="row">
	<div class="col">1</div>
	<div class="col">2</div>
	<div class="col">3</div>
	<div class="col">4</div>
	<div class="col">5</div>
	<div class="col">6</div>
	<div class="col">7</div>
	<div class="col">8</div>
	<div class="col">9</div>
	<div class="col">10</div>
	<div class="col">11</div>
	<div class="col">12</div>
</div>

First, we will tell that the row will be a grid having 12 columns in total. While having each column equally sized.

.row {
	display: grid;
	grid-template-columns: repeat(12, 1fr);
	grid-gap: 5px;
}

Media Query for Desktop

For desktop devices, you can write the following media query in CSS.

/* for desktop */
@media (min-width: 992px) {
	.col {
		grid-column: auto/span 1;
	}
}

It will check if the device width exceeds 992px, then it will divide the column into 12 parts. i.e. 12 / 1 = 12 columns

Media Query for Tablet

The following media query will be used for tablet devices.

/* for tablets */
@media (min-width: 768px) and (max-width: 991px) {
	.col {
		grid-column: auto/span 3; /* 12 / 3 = 4 columns for tablet */
	}
}

Media Queries for Mobile and Small Devices

For mobile devices, we will show 2 columns, and for small phones (having a resolution of less than 767px) we will show 1 column.

/* for mobile */
@media (max-width: 767px) {
	.col {
		grid-column: auto/span 6; /* 12 / 6 = 2 columns for mobile */
	}
}

/* for small devices */
@media (max-width: 320px) {
	.col {
		grid-column: auto/span 12; /* 12 / 12 = 1 column for small devices */
	}
}

That’s it. That’s how you can use media queries in CSS and make your website responsive for all devices. If you face any problem in following this, kindly do let me know.

Show UI if a variable is true – React JS

In this article, we will discuss how you can hide or show any UI if the value of a variable is true in React JS. Following this tutorial, you will also learn how to use the if condition in React JS. You just need to do 3 things:

  1. Import useState from “react”
  2. Create a variable
  3. Show UI only if that variable is true

Here is the code:

import { useState } from "react"

function App() {

  const [showButton, setShowButton] = useState(false)

  return (
    <button>Always show</button>

    { showButton && (
        <button>
          Show only when required
        </button>
    ) }
  )
}

export default App

By default, you will not see the second button because the default value is false. Try changing the value of the variable from false to true, you will start seeing the UI.

Check out our more tutorials on React JS.

Routing in React JS

Routing in React JS can be achieved using a module “react-router-dom”. This module provides all the functionality required for creating links and displaying components based on the current route.

Installing “react-router-dom”

First, you need to install this module by running the following command at the root of your project:

npm install react-router-dom

Creating routes

Then open the “src/App.js” file and import BrowserRouter from “react-router-dom”.

// src/App.js

import { BrowserRouter } from "react-router-dom"

Then wrap all the tags of function App() inside BrowserRouter.

function App() {
  return (
    <BrowserRouter>
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>

          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </header>
      </div>
    </BrowserRouter>
  );
}

Then import Routes from “react-router-dom” and create its tag where you want to display the component when a specific link is accessed.

import { BrowserRouter, Routes } from "react-router-dom"

function App() {
  return (
    <BrowserRouter>
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>

          <Routes>
            
          </Routes>

          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </header>
      </div>
    </BrowserRouter>
  );
}

After that, import Route from “react-router-dom” and create as many routes as required inside the Routes tag.

import { BrowserRouter, Routes, Route } from "react-router-dom"

function App() {
  return (
    <BrowserRouter>
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>

          <Routes>
              <Route path="/" element={ <Home /> } />
              <Route path="/About" element={ <About /> } />
          </Routes>

          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </header>
      </div>
    </BrowserRouter>
  );
}

Then you need to import these components.

import Home from "./components/Home"
import About from "./components/About"

function App() {
	...
}

Creating components

Create a folder named “components” inside your “src” folder and create 2 files in it.

  1. src/components/Home.js
  2. src/components/About.js

Following will be the code of these 2 files.

// src/components/Home.js

function Home() {
	return (
		<h1>Home</h1>
	)
}

export default Home
// src/components/About.js

function About() {
	return (
		<h1>About</h1>
	)
}

export default About

At this point, you will see the Home component at the main route.

Routing in React JS - Home route
Routing in React JS – Home route

Creating navigation links

Now we need to create navigation links for each route. So import the Link from “react-router-dom” and create 2 links from it.

import { BrowserRouter, Routes, Route, Link } from "react-router-dom"

function App() {
  return (
    <BrowserRouter>
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>

          <Routes>
              <Route path="/" element={ <Home /> } />
              <Route path="/About" element={ <About /> } />
          </Routes>

          <Link to="/" style={{
            color: "white"
          }}>
            Home
          </Link>

          <Link to="/About" style={{
            color: "white"
          }}>
            About
          </Link>

          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </header>
      </div>
    </BrowserRouter>
  );
}

If you refresh the page now, you will see 2 links. On clicking any link, you will see that its relevant component is displayed.

Routing in React JS - Navigation links
Routing in React JS – Navigation links

Additional: Lazy load components

You can also lazy load your components, which means that your component will only be imported when it is accessed. It is great for larger apps where a large number of components are being created. For that, first, you need to import lazy from “react”.

import { lazy } from "react"

Then you need to change the way you are importing your components.

// import Home from "./components/Home"
// import About from "./components/About"

const Home = lazy(function () {
  return import ("./components/Home")
})

const About = lazy(function () {
  return import ("./components/About")
})

When lazy loading your components, you need to wrap your <Routes> tag inside Suspense. So import it and wrap your routes inside it.

import { lazy, Suspense } from "react"

function App() {
  return (
    <BrowserRouter>
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>

          <Suspense fallback={ <h3>Loading...</h3> }>
            <Routes>
              <Route path="/" element={ <Home /> } />
              <Route path="/About" element={ <About /> } />
            </Routes>
          </Suspense>

          <Link to="/" style={{
            color: "white"
          }}>
            Home
          </Link>

          <Link to="/About" style={{
            color: "white"
          }}>
            About
          </Link>

          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </header>
      </div>
    </BrowserRouter>
  );
}

fallback is used to display a UI component until the actual component gets loaded.

So that’s it. That’s how you can create routing in your React JS app. If you face any issues in following this, kindly do let me know. I created a Social Networking website in React JS that uses this routing mechanism. You can download it from here for free.

How to create a new React JS project

Many people want to learn React JS, but they don’t know where to start. The most basic thing is to start by creating a new project in React JS. To create a new React JS project, you first need to make sure you have Node.js installed in your system. If you do not have Node.js installed in your system, you can download it from here. Try downloading the LTS version.

Once you have Node.js installed in your system, run the following command:

npm install -g npx

This will install the NPX module globally. NPX is a command-line tool used to run NPM packages directly without needing to install them locally or globally.

Then run the following command to create a new folder for your React JS project:

npx create-react-app my-react-app

Replace “my-react-app” with the folder name you want to be created. If you are planning to give spaces in the name of the folder, enclose them in double quotes “”. This will create a new folder named “my-react-app”. Open the terminal inside this folder and run the React JS project.

cd my-react-app
npm start

At this point, you will see the following page. It will automatically be opened in your browser:

Create new React JS project
Create new React JS project

We created a free Social Network project in React JS. You can download it and see the code to learn more.

Update all dependencies at once in NPM

To update all dependencies in your project using NPM, you need to use the module “npm-check-updates” (NCU) globally and run its command:

npm install -g npm-check-updates
ncu -u
npm install
  1. npm install -g npm-check-updates: This will install the “npm-check-updates” module globally in your system. So you will be able to run the command “ncu” directly in your terminal.
  2. ncu -u: This will update your package.json
  3. npm install: This will finally update all your modules inside the “node_modules” folder.

If you face any problem with this, kindly do let me know.

Call class method from variable – PHP

Sometimes you have to call the class method from the PHP variable. Let’s say you have a class with few functions with arguments.

<?php

class User
{
	public function list()
	{
		echo "Users list";
	}
	
	public function fetch($id)
	{
		echo "User fetch: " . $id;
	}
	
	public function update($id, $name)
	{
		echo "User update: " . $id . ", " . $name;
	}
}

Then you can create the class object from a variable like the following:

<?php

class User
{
	public function list()
	{
		echo "Users list";
	}
	
	public function fetch($id)
	{
		echo "User fetch: " . $id;
	}
	
	public function update($id, $name)
	{
		echo "User update: " . $id . ", " . $name;
	}
}

$class_name = "User";
$class_obj = new $class_name();

Now to call the method from that object, you can do:

<?php

class User
{
	public function list()
	{
		echo "Users list";
	}
	
	public function fetch($id)
	{
		echo "User fetch: " . $id;
	}
	
	public function update($id, $name)
	{
		echo "User update: " . $id . ", " . $name;
	}
}

$class_name = "User";
$class_obj = new $class_name();

$action_name = "list";
$class_obj->{$action_name}(); // echo "Users list"

You can also pass parameters to the method as well.

<?php

class User
{
	public function list()
	{
		echo "Users list";
	}
	
	public function fetch($id)
	{
		echo "User fetch: " . $id;
	}
	
	public function update($id, $name)
	{
		echo "User update: " . $id . ", " . $name;
	}
}

$class_name = "User";
$class_obj = new $class_name();

$action_name = "fetch";
$class_obj->{$action_name}(3); // echo "User fetch 3"

You can call multiple parameters as well.

<?php

class User
{
	public function list()
	{
		echo "Users list";
	}
	
	public function fetch($id)
	{
		echo "User fetch: " . $id;
	}
	
	public function update($id, $name)
	{
		echo "User update: " . $id . ", " . $name;
	}
}

$class_name = "User";
$class_obj = new $class_name();

$action_name = "update";
$class_obj->{$action_name}(5, "Adnan"); // echo "User update 5, Adnan"

Full code:

<?php

class User
{
	public function list()
	{
		echo "Users list";
	}
	
	public function fetch($id)
	{
		echo "User fetch: " . $id;
	}

	public function update($id, $name)
	{
		echo "User update: " . $id . ", " . $name;
	}
}

$class_name = "User";
$class_obj = new $class_name();

$action_name = "list";
$class_obj->{$action_name}(); // echo "Users list"

echo "<br />";

$action_name = "fetch";
$class_obj->{$action_name}(3); // echo "User fetch 3"

echo "<br />";

$action_name = "update";
$class_obj->{$action_name}(5, "Adnan"); // echo "User update 5, Adnan"

I have used this technique to create a lightweight PHP framework. Check out our other tutorials on PHP.

Custom routes – Htaccess tutorial

In this htaccess tutorial, you will learn how to create custom routes. You will also learn how you can prevent file listing using htaccess.

Video tutorial:

You need to create a file named “.htaccess” (note the dot at the start) at the root of your project. To prevent directory listing, write the following line in the “.htaccess” file.

Options -Indexes

Before using any routing rules and conditions, we must first activate them. Write the following line to activate the rewrite rules.

Options -Indexes
RewriteEngine On

Then we need to make sure the requests do not match any directory, file name, or symbolic link.

The following line checks if the requested file name is not a directory.

Options -Indexes
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d

The following line checks if the requested file name is not a file.

Options -Indexes
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

The following line checks if the requested file name is not a symbolic link.

Options -Indexes
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

Example 1:

Now, let’s say you want to redirect all the requests from the “users/list” route to the “users-list.php” file. You can do that by adding the following line in your htaccess file.

Options -Indexes
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^users/list$ users-list.php [L]

^ means the start of the string.

$ means the end of the string.

[L] means to stop looking for more RewriteRule if this condition matches.

Example 2:

Now let’s say you want to redirect all requests from the “users/fetch/1” route to the “user-by-id.php” file. Here, the last “1” is the parameter you want to send. Now to redirect the request to the file, you need to add the following rule:

Options -Indexes
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^users/list$ users-list.php [L]
RewriteRule ^users/fetch/([0-9]+)$ user-by-id.php?id=$1 [QSA,L]

([0-9]+) will match for any integer number.

?id=$1 means that it will send the parameter named “id“, with the value matched from the previous regular expression, to the file “user-by-id.php“.

QSA (Query String Append) will make sure to append the existing query string (if any) while preserving the additional parameters (id=1 in this case) to the URL.

Then in the “user-by-id.php” file, you can get the ID using the following code:

<?php

echo $_GET["id"];

?>

Example 3:

For instance, if you want to redirect the URL “users/fetch/adnan” (‘adnan’ is the argument) to the file “user-by-name.php“, you can do that by adding the following rewrite rule.

Options -Indexes
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^users/list$ users-list.php [L]
RewriteRule ^users/fetch/([0-9]+)$ user-by-id.php?id=$1 [QSA,L]
RewriteRule ^users/fetch/([a-zA-Z\s-]+)$ user-by-name.php?name=$1 [QSA,NC,L]

([a-zA-Z\s-]+) This regular expression will match all alphabets, including multiple words, letters, spaces, and hyphens.

NC This flag will make the match case insensitive.

Then in the “user-by-name.php” file, you can get the name using the following code:

<?php

echo $_GET["name"];

?>

Following is the complete code of the “.htaccess” file.

Options -Indexes
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^users/list$ users-list.php [L]
RewriteRule ^users/fetch/([0-9]+)$ user-by-id.php?id=$1 [QSA,L]
RewriteRule ^users/fetch/([a-zA-Z\s-]+)$ user-by-name.php?name=$1 [QSA,NC,L]

Download:

custom-routes-htaccess.zip

If you are running on HTTP, you can make your web server redirect the HTTP requests to HTTPS following this tutorial.

I also created a simple and lightweight PHP MVC framework using this htaccess rewrite condition. You can check it out here.

This concludes our htaccess tutorial on creating custom routes. If you face any issues with this, kindly let me know.

TrustPilot clone – PHP, MySQL, Laravel

A clone of TrustPilot website is created in PHP and MySQL using Laravel framework version 11. For frontend rendering, I am using Vue JS 3 and on admin side I am using React JS.

Files included:

  • .php
  • .css
  • .js

Features:

  1. User can post reviews about a company.
  2. Can flag a review.
  3. Can share reviews on social media.
  4. Company owners can claim a company by verifying their email address.
  5. Automatically takes screenshot of a company home page.
  6. Admin can add companies from admin panel.
  7. Admin can view all reviews, flags and claims.

Demo:

Show loader on AJAX – VueJS

Today, you will learn, how you can show a loader in VueJS when an AJAX is called. We will be using Axios library for calling AJAX request.

If you do not want to use Axios library, you can use the default XMLHttpRequest object of Javascript. Learn how to do it from here.

Video tutorial:

Let’s say we have the following code that:

  1. Includes VueJS and Axios library.
  2. Create a div for Vue app.
  3. Mount Vue app onto the div.
  4. On mounted, calls an AJAX request.
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<div id="app"></div>

And following javascript code will mount the Vue app.

Vue.createApp({
	async mounted() {
		const response = await axios.post(
			"https://api.github.com/users/adnanafzal565"
		)
		
		console.log(response)
	}
}).mount("#app")

Now, I will create a loading text that will be displayed only if the loading variable is true.

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<div id="app">
	<p v-if="loading">Loading...</p>
</div>

Then I will create that variable in my Vue app and initialize it as false.

Vue.createApp({

	data() {
		return {
			loading: false
		}
	},

	async mounted() {
		const response = await axios.post(
			"https://api.github.com/users/adnanafzal565"
		)
		
		console.log(response)
	}
}).mount("#app")

Lastly, we are going to set this variable to true before calling the AJAX and false after the AJAX is finished.

Vue.createApp({

	data() {
		return {
			loading: false
		}
	},

	async mounted() {
		this.loading = true
		
		const response = await axios.post(
			"https://api.github.com/users/adnanafzal565"
		)
		
		this.loading = false
		
		console.log(response)
	}
}).mount("#app")

So that’s it. That’s how you can show a loader while AJAX is being called in VueJS.

Save and display images in Binary – NodeJS

In this tutorial, you will learn, how you can save and display images in Binary in NodeJS and MongoDB.

We will also create an API that will return a binary image as a response.

Saving images in the database has many advantages over saving images in file storage.

  1. First, if you are deploying in Heroku, they do not provide persistent storage for their free tier. This means that the files uploaded on Heroku will automatically be removed after 30 minutes of inactivity.
  2. Second, migrating from one deployment platform to another is easy. Since you do not have to move all the uploaded files too. You can use mongodb.com for your MongoDB database and use this on all platforms.
  3. Third, we will be saving images in Binary format so it will take less space than saving in Base64.

Video tutorial:

The following route will save the user-uploaded image as Binary in MongoDB using NodeJS.

// npm install fs
// import file system module
const fs = require("fs")

app.post("/upload", async function (request, result) {
    // get user-uploaded file
    const image = request.files.image
  
    // reading file data
    const fileData = await fs.readFileSync(image.path)
    
    // converting to binary
    const binary = Buffer.from(fileData)
    
    // saving in database
    await db.collection("images").insertOne({
        path: binary
    })
    
    // sending response back to client
    result.send("Done")
})

Check out this tutorial if you want to know how to connect with MongoDB.

Now that the image has been saved, we will create a GET route that will return the image as a base64 string.

// set EJS as templating engine
app.set("view engine", "ejs")

app.get("/", async function (request, result) {
    // get image from collection
    const image = await db.collection("images")
        .findOne({})
        
    // variable to get base64 string
    let imageString = ""
    
    // check if document exists
    if (image != null) {
        // image.path will return binary
        // buffer() function is called on binary object
        imageString = "data:image/png;base64," + image.path.buffer.toString("base64")
    }
    
    // sending data to file "views/index.ejs"
    result.render("index", {
        image: imageString
    })
})

After that, we need to create a folder named “views” and inside it a file named “index.ejs” and write the following code in it:

<img src="<%= image %>" style="width: 100%;" />

That’s how you can save and display images in Binary in NodeJS and MongoDB.