In this article, we see how easily we can create an Image Gallery with a preview feature using HTML, CSS, and some JavaScript.
Approach: We will follow the below-described approach
HTML:
- Create a div with a class container.
- Create two more div inside the first div one for the main view and the other for the side view with classes main_view and side_view.
- Inside the main view insert one image tag with the id main.
- Inside the side view insert all other images of the gallery with function change and pass the src of the image to function.
CSS:
- Give width and margin to a container.
- Give the height and width to a main_view.
- Set the dimensions of the image in the main_view.
- Set side_view to display all images in proper dimensions using flex.
JavaScript: Using the change function we will just replace the src of main_view with the source of the clicked image.
HTML
<!DOCTYPE html> < html > Â Â < body > Â Â Â Â Â Â <!-- Container for our gallery --> Â Â Â Â < div class = "container" > Â Â Â Â Â Â Â Â <!-- Main view of our gallery --> Â Â Â Â Â Â Â Â < div class = "main_view" > Â Â Â Â Â Â Â Â Â Â Â Â < img src = "one.jpg" id = "main" alt = "IMAGE" > Â Â Â Â Â Â Â Â </ div > Â Â Â Â Â Â Â Â Â Â <!-- All images with side view --> Â Â Â Â Â Â Â Â < div class = "side_view" > Â Â Â Â Â Â Â Â Â Â Â Â < img src = "one.jpg" onclick = "change(this.src)" > Â Â Â Â Â Â Â Â Â Â Â Â < img src = "two.jpg" onclick = "change(this.src)" > Â Â Â Â Â Â Â Â Â Â Â Â < img src = "three.jpg" onclick = "change(this.src)" > Â Â Â Â Â Â Â Â Â Â Â Â < img src = "four.jpg" onclick = "change(this.src)" > Â Â Â Â Â Â Â Â </ div > Â Â Â Â </ div > </ body > Â Â Â Â </ html > |
CSS
/*Setting Basic Dimensions to give     gallery view */ .container {     margin : 0 auto ;     width : 90% ; }   .main_view {     width : 80% ;     height : 25 rem; }   .main_view img {     width : 100% ;     height : 100% ;     object-fit: cover; }   .side_view {     display : flex;     justify- content : center ;     flex-wrap: wrap; }   .side_view img {     width : 9 rem;     height : 7 rem;     object-fit: cover;     cursor : pointer ;     margin : 0.5 rem; } |
Javascript
const change = src => { Â Â Â Â document.getElementById( 'main' ).src = src } |
Output: Click here to see the live Output.