Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create a list grid view with CSS and JavaScript?
To create a list grid view, the code is as follows −
Example
<!DOCTYPE html>
<html>
<head>
<style>
* {
box-sizing: border-box;
}
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
/* Create two equal columns that floats next to each other */
.column {
float: left;
width: 50%;
padding: 10px;
color: white;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
/* Style the buttons */
.btn {
border: none;
outline: none;
padding: 12px 16px;
background-color: #f1f1f1;
cursor: pointer;
}
.btn:hover {
background-color: #ddd;
}
.btn.active {
background-color: #666;
color: white;
}
</style>
</head>
<body>
<h1>List Grid view example</h1>
<h2>Click on the below buttons to switch views</h2>
<div id="btnContainer">
<button class="btn" onclick="listView()">List</button>
<button class="btn active" onclick="gridView()">Grid</button>
</div>
<br />
<div class="row">
<div class="column" style="background-color:rgb(154, 9, 173);">
<h2>Column 1</h2>
</div>
<div class="column" style="background-color:rgb(113, 35, 216);">
<h2>Column 2</h2>
</div>
</div>
<div class="row">
<div class="column" style="background-color:rgb(19, 143, 85);">
<h2>Column 3</h2>
</div>
<div class="column" style="background-color:rgb(207, 69, 27);">
<h2>Column 4</h2>
</div>
</div>
<script>
var elements = document.querySelectorAll(".column");
function listView() {
Array.from(elements).forEach(item => {
item.style.width = "100%";
});
Array.from(document.querySelectorAll(".btn")).forEach((item, index) => {
if (index === 0) item.classList.add("active");
else item.classList.remove("active");
});
}
function gridView() {
Array.from(elements).forEach(item => {
item.style.width = "50%";
});
Array.from(document.querySelectorAll(".btn")).forEach((item, index) => {
if (index === 1) item.classList.add("active");
else item.classList.remove("active");
});
}
</script>
</body>
</html>
Output
The above code will produce the following output −

On clicking the list button −

Advertisements