"; 3. Use the "function showBgImg(e) {...}" method to achieve the effect of clicking on the image to enlarge it."/> "; 3. Use the "function showBgImg(e) {...}" method to achieve the effect of clicking on the image to enlarge it.">
search
HomeWeb Front-endFront-end Q&AHow to achieve click-to-enlarge image using pure css

Pure CSS method to achieve click-to-enlarge images: 1. Create an HTML sample file; 2. Set "

"; 3. Use the "function showBgImg(e) {...}" method to achieve the effect of clicking on the image to enlarge it .

How to achieve click-to-enlarge image using pure css

The operating environment of this tutorial: Windows 10 system, HTML5&&CSS3 version, DELL G3 computer

How to use pure css to click on the image to enlarge it?

Css actual training picture, click to enlarge

I. Background

This is a very common function, usually displayed on the website It's a thumbnail. After you click on the thumbnail, the enlarged picture will be displayed in a pop-up box

So how is this function implemented? I just learned the basic knowledge of CSS, and now I can do the actual thing Operation

1. Idea

First split the structure of the page:

  • There is a pop-up window that displays a large image in the pop-up window; and The pop-up window is hidden by default
  • You can place many pictures on the main page and add click events
  • After clicking, the pop-up window displays and displays the big picture
  • Click on the big picture After the following, close the pop-up window

II. Implementation

According to the above description, we first implement a basic version, first write HTML

<body>

<!-- 先来实现弹窗 -->
<div class=&#39;modal&#39; id=&#39;modal&#39;>
    <img  src="/static/imghwm/default1.png"  data-src="https://img.php.cn/upload/image/622/244/178/1674887775582644.jpg?x-oss-process=image/resize,p_40"  class="lazy"  id=&#39;bgImg&#39; / alt="How to achieve click-to-enlarge image using pure css" >
</div>


<!-- 下面则是主页内容,先只给几个图片 -->

<div>
    <img src="/static/imghwm/default1.png"  data-src="https://img.php.cn/upload/image/622/244/178/1674887775582644.jpg?x-oss-process=image/resize,p_40"  class="lazy"  class=&#39;thum-img&#39; 
    src=&#39;http://f.hiphotos.baidu.com/image/pic/item/80cb39dbb6fd5266cdb2ba16a718972bd4073612.jpg&#39; />
</div>

</body>

Then add the corresponding style, which requires the modal to be hidden by default, so as follows (in order to better distinguish the pop-up window, the background color and border are added)

<style>
.modal {
    display: none;
    margin: auto;
    width: 80%;
    height: 80%;
    background-color: rgb(0, 0, 0, 0.89);
    z-index: 1;
    border: 1px solid rgb(255,255,255,1);
}

.modal>img {
    display: block;
    margin: auto;
    padding: 10%;
    max-width: 60%;
    max-height: 60%;
}

.thum-img {
    width: 200px;
    height: 200px;
    margin: auto;
    display: block;
    padding: 40px;
}

</style>

The next step is to click on the logic of displaying the large image, which is implemented with the help of js.

<script>
    var modal = document.getElementById(&#39;modal&#39;);
    var bgImg = document.getElementById(&#39;bgImg&#39;);
    var thumImg = document.getElementById(&#39;thumImg&#39;);
    thumImg.onclick = function() {
        modal.style.display = &#39;block&#39;;
        bgImg.src = this.src;
    }

    bgImg.onclick = function() {
        modal.style.display = &#39;none&#39;;
    }
</script>

After assembling the above implementation into an html, test it directly and view it. The demonstration effect is as follows

How to achieve click-to-enlarge image using pure css

Although the above has achieved the results we expected, there are a few points that we are not satisfied with.

  • is not the pop-up effect we expected. The original The picture is squeezed down
  • It would be better if there is an enlarged animation effect in the pop-up window (just can use the animation learned before)
  • When there are many pictures in the picture, How to click to enlarge

III. Advanced

First of all, if you want it to be a real pop-up window without affecting the existing layout, you usually do it by setting the position, as we do You can add another layer outside the modal to become

<div style=&#39;position:fixed&#39;>
    <div class=&#39;modal&#39; id=&#39;modal&#39;>
        <img  src="/static/imghwm/default1.png"  data-src="https://img.php.cn/upload/image/742/960/488/1674887791873102.jpg?x-oss-process=image/resize,p_40"  class="lazy"  id=&#39;bgImg&#39; / alt="How to achieve click-to-enlarge image using pure css" >
    </div>
</div>

The second is that the style of the pop-up window is too ugly. We can use the border shadow we learned before to achieve a beautiful pop-up effect,

  • Change to fill the background of all images
  • Remove the background color, add a shadow, and add a white border

The modified css is as follows

.modal {
    display: none;
    margin: auto;
    padding-top: 5%;
    width: 50%;
    height: 80%;
    z-index: 1;
    background-color: white;
}

.modal img {
    display: block;
    padding: 10px;
    margin: auto;
    max-width: 100%;
    max-height: 100%;
    box-shadow: 0 2px 6px rgb(0, 0, 0, 0.2), 0 10px 20px rgb(0, 0, 0, 0.2);
    border-radius: 12px;
    border: 1px solid white;
}

Next consider adding animation and a magnification effect

@keyframes zoom {
    from {transform: scale(0.1)}
    to {transform: scale(1)}
}

.modal img {
    animation-name: zoom;
    animation-duration: 0.6s;
}

Then let’s look at the demonstration effect as follows

How to achieve click-to-enlarge image using pure css

The next step is to turn this into a universal solution to support multiple images. This is mainly a modification of the image click event. Just make some changes to the hard-coded parts above

How to achieve click-to-enlarge image using pure css

IV. Source code

Finally give all the source code

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>小灰灰css学习笔记</title> 
<style>
#modal {
	display: none;
}
.modal {
    margin: auto;
    padding-top: 5%;
    width: 50%;
    height: 80%;
    z-index: 1;
}

.modal img {
    animation-name: zoom;
	animation-duration: 0.6s;
    display: block;
    padding: 10px;
    margin: auto;
    max-width: 100%;
    max-height: 100%;
    box-shadow: 0 2px 6px rgb(0, 0, 0, 0.2), 0 10px 20px rgb(0, 0, 0, 0.2);
    border-radius: 12px;
    border: 1px solid white;
}

@keyframes zoom {
    from {transform: scale(0.1)}
    to {transform: scale(1)}
}

.thum-img {
    float: left;
    width: 200px;
    height: 200px;
    margin: auto;
    display: block;
    padding: 40px;
}
</style>
	</head>
<body>
<!-- 先来实现弹窗 -->
<div style=&#39;position:fixed;width:100%;height:100%;background-color:rgb(0,0,0,0.65)&#39; id=&#39;modal&#39;>
<div class=&#39;modal&#39; id=&#39;modalw&#39;>
    <img  id=&#39;bgImg&#39; / alt="How to achieve click-to-enlarge image using pure css" >
</div>
</div>


<!-- 下面则是主页内容,先只给几个图片 -->

<div>
    <img onclick=&#39;showBgImg(this)&#39; class=&#39;thum-img&#39; 
    src=&#39;http://f.hiphotos.baidu.com/image/pic/item/80cb39dbb6fd5266cdb2ba16a718972bd4073612.jpg&#39; />
 	<img  class=&#39;thum-img&#39; src=&#39;http://a.hiphotos.baidu.com/image/pic/item/e61190ef76c6a7ef5e886d03f1faaf51f3de666d.jpg&#39; onclick=&#39;showBgImg(this)&#39;/ alt="How to achieve click-to-enlarge image using pure css" > 
    <img  class=&#39;thum-img&#39; src=&#39;http://g.hiphotos.baidu.com/image/pic/item/730e0cf3d7ca7bcb747b4a5cb2096b63f624a845.jpg&#39; onclick=&#39;showBgImg(this)&#39;/ alt="How to achieve click-to-enlarge image using pure css" >
    <img  class=&#39;thum-img&#39; src=&#39;http://c.hiphotos.baidu.com/image/pic/item/b21c8701a18b87d6657856e70c0828381f30fd14.jpg&#39; onclick=&#39;showBgImg(this)&#39;/ alt="How to achieve click-to-enlarge image using pure css" >
    <img  class=&#39;thum-img&#39; src=&#39;https://raw.githubusercontent.com/liuyueyi/Source/master/img/info/blogInfoV2.png&#39; onclick=&#39;showBgImg(this)&#39;/ alt="How to achieve click-to-enlarge image using pure css" >
</div>

<script>
    var modal = document.getElementById(&#39;modal&#39;);
    var bgImg = document.getElementById(&#39;bgImg&#39;);


    function showBgImg(e) {
		modal.style.display = &#39;block&#39;;
		bgImg.src = e.src;
	}

	bgImg.onclick = function() {
		modal.style.display = &#39;none&#39;;
	}
</script>
</body>
</html>
recommends learning: "css video tutorial"

The above is the detailed content of How to achieve click-to-enlarge image using pure css. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
React Inside HTML: Integrating JavaScript for Dynamic Web PagesReact Inside HTML: Integrating JavaScript for Dynamic Web PagesApr 16, 2025 am 12:06 AM

To integrate React into HTML, follow these steps: 1. Introduce React and ReactDOM in HTML files. 2. Define a React component. 3. Render the component into HTML elements using ReactDOM. Through these steps, static HTML pages can be transformed into dynamic, interactive experiences.

The Benefits of React: Performance, Reusability, and MoreThe Benefits of React: Performance, Reusability, and MoreApr 15, 2025 am 12:05 AM

React’s popularity includes its performance optimization, component reuse and a rich ecosystem. 1. Performance optimization achieves efficient updates through virtual DOM and diffing mechanisms. 2. Component Reuse Reduces duplicate code by reusable components. 3. Rich ecosystem and one-way data flow enhance the development experience.

React: Creating Dynamic and Interactive User InterfacesReact: Creating Dynamic and Interactive User InterfacesApr 14, 2025 am 12:08 AM

React is the tool of choice for building dynamic and interactive user interfaces. 1) Componentization and JSX make UI splitting and reusing simple. 2) State management is implemented through the useState hook to trigger UI updates. 3) The event processing mechanism responds to user interaction and improves user experience.

React vs. Backend Frameworks: A ComparisonReact vs. Backend Frameworks: A ComparisonApr 13, 2025 am 12:06 AM

React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

HTML and React: The Relationship Between Markup and ComponentsHTML and React: The Relationship Between Markup and ComponentsApr 12, 2025 am 12:03 AM

The relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.

React and the Frontend: Building Interactive ExperiencesReact and the Frontend: Building Interactive ExperiencesApr 11, 2025 am 12:02 AM

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React and the Frontend Stack: The Tools and TechnologiesReact and the Frontend Stack: The Tools and TechnologiesApr 10, 2025 am 09:34 AM

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

React's Role in HTML: Enhancing User ExperienceReact's Role in HTML: Enhancing User ExperienceApr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!