search
HomeWeb Front-endHTML TutorialThree methods in HTML to implement the img tag to only display the sample code in the center of the picture

html中img tag Display imageCenter method currently I know three methods. The editor will share them to the Script House platform below. Friends who need them can refer to the method of displaying the center of the image in the img tag in the

. Currently, I know three methods. I will record them here.

The first one: using css clip:rect(top right bottom left ); Usage needs to be used with position: absolute: as follows


##

<img src="/static/imghwm/default1.png"  data-src="http://img2.utuku.china.com/640x0/news/20170210/77b8b5ca-11d3-4307-9a93-c12df5eb1a35.jpg"  class="lazy"  
     style="position: absolute;clip: rect(0px,250px,200px,50px);width: 300px;height: 200px">

Set the width and height of the image to be equivalent Scale proportionally to the actual width and height of the image, and then use the rect method to set the clipping range of the image.

##- Second: Use img’s background#. ##Attributes:

<style type="text/css">
        img {
            background-image: url(http://img2.utuku.china.com/640x0/news/20170210/77b8b5ca-11d3-4307-9a93-c12df5eb1a35.jpg);//设置背景图片
            background-repeat: no-repeat;//背景图像将仅显示一次。
            background-attachment: scroll;//
            background-position: -50px 0px;//设置背景图片的的偏移量,这个-50相当于背景整体向左偏移50,就可以显示图片的中心
            background-size: 300px 200px;////设置背景图片的大小,相当于图片实际宽高等比例饿缩放的
            background-color: transparent;//
            width: 200px;//
            height: 200px;//
        }
    </style>

Use the background to control the center position of the image display. You need to set the background to scale according to the true width and height of the image. Then offset the movement amount of the background to control the width and height of the picture. What needs to be noted is that the src of the picture cannot be set. When the img tag does not set src, a gray border will appear on the displayed picture, and there is no way to remove it. b
ord

er:0px also has no effect. My previous solution was to put a default fully transparent image in src, which will solve the problem.

The third method: Contain img in p, use p's

overflow: hidden; to control it, it is more flexible to use,

<p style="width: 100px;height: 100px;overflow: hidden">
<img  src="/static/imghwm/default1.png"  data-src="http://img2.utuku.china.com/640x0/news/20170210/77b8b5ca-11d3-4307-9a93-c12df5eb1a35.jpg"  class="lazy"     style="max-width:90%" id="img_id" alt="Three methods in HTML to implement the img tag to only display the sample code in the center of the picture" >
</p>
<script>
    var img = document.getElementById("img_id");
    var image = new Image();
    var realWidth = 0;//储存图片实际宽度
    var realHeight = 0;//储存图片实际高度
    //获取图片的宽高
    image.src = "http://img2.utuku.china.com/640x0/news/20170210/77b8b5ca-11d3-4307-9a93-c12df5eb1a35.jpg";
    //加载成功的处理
    image.onload = function () {
        realWidth = image.width;//获取图片实际宽度
        realHeight = image.height;//获取图片实际高度
        //让img的宽高相当于图片实际宽高的等比缩放,然后再偏移
        if (realWidth > realHeight){
            img.width = (100/realHeight)*realWidth;//等比缩放宽度
            img.height = 100;//跟p高度一致
            img.style.left = &#39;-&#39; + ((100/realHeight)*realWidth-100)/2 + &#39;px&#39;;//设置图片相对自己位置偏移为img标签的宽度-高度的一半
        }else if (realWidth < realHeight){
            img.width =100 ;//跟p高度一致
            img.height = (100/realWidth)*realHeight;//等比缩放高度
            img.style.top = &#39;-&#39; + ((100/realWidth)*realHeight-100)/2 + &#39;px&#39;;//设置图片相对自己位置偏移为img标签的高度-宽度的一半
        }else {
            img.width =100 ;
            img.height = 100;
        }
    };
    //图片加载失败的处理
    img.onerror = function () {
        img.src = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1492076382452&di=04ebd6c4688b2ffbd8ae18e685234704&imgtype=0&src=http%3A%2F%2Fd.hiphotos.baidu.com%2Fzhidao%2Fwh%253D450%252C600%2Fsign%3D0c96dc86da33c895a62b907fe4235fc6%2F0823dd54564e9258d2bb2dff9f82d158ccbf4e17.jpg";
        img.width =100 ;
        img.height = 100;
    }
</script>

above
Comments

It is already very clear, mainly p controls the size, and the img tag adjusts its size according to the size of p, so as to display the middle part of the picture. Personally, I think it is the third way. The method is easier to use.

The above is the detailed content of Three methods in HTML to implement the img tag to only display the sample code in the center of the picture. 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
What are self-closing tags? Give an example.What are self-closing tags? Give an example.Apr 27, 2025 am 12:04 AM

Self-closingtagsinHTMLandXMLaretagsthatclosethemselveswithoutneedingaseparateclosingtag,simplifyingmarkupstructureandenhancingcodingefficiency.1)TheyareessentialinXMLforelementswithoutcontent,ensuringwell-formeddocuments.2)InHTML5,usageisflexiblebutr

Beyond HTML: Essential Technologies for Web DevelopmentBeyond HTML: Essential Technologies for Web DevelopmentApr 26, 2025 am 12:04 AM

To build a website with powerful functions and good user experience, HTML alone is not enough. The following technology is also required: JavaScript gives web page dynamic and interactiveness, and real-time changes are achieved by operating DOM. CSS is responsible for the style and layout of the web page to improve aesthetics and user experience. Modern frameworks and libraries such as React, Vue.js and Angular improve development efficiency and code organization structure.

What are boolean attributes in HTML? Give some examples.What are boolean attributes in HTML? Give some examples.Apr 25, 2025 am 12:01 AM

Boolean attributes are special attributes in HTML that are activated without a value. 1. The Boolean attribute controls the behavior of the element by whether it exists or not, such as disabled disable the input box. 2.Their working principle is to change element behavior according to the existence of attributes when the browser parses. 3. The basic usage is to directly add attributes, and the advanced usage can be dynamically controlled through JavaScript. 4. Common mistakes are mistakenly thinking that values ​​need to be set, and the correct writing method should be concise. 5. The best practice is to keep the code concise and use Boolean properties reasonably to optimize web page performance and user experience.

How can you validate your HTML code?How can you validate your HTML code?Apr 24, 2025 am 12:04 AM

HTML code can be cleaner with online validators, integrated tools and automated processes. 1) Use W3CMarkupValidationService to verify HTML code online. 2) Install and configure HTMLHint extension in VisualStudioCode for real-time verification. 3) Use HTMLTidy to automatically verify and clean HTML files in the construction process.

HTML vs. CSS and JavaScript: Comparing Web TechnologiesHTML vs. CSS and JavaScript: Comparing Web TechnologiesApr 23, 2025 am 12:05 AM

HTML, CSS and JavaScript are the core technologies for building modern web pages: 1. HTML defines the web page structure, 2. CSS is responsible for the appearance of the web page, 3. JavaScript provides web page dynamics and interactivity, and they work together to create a website with a good user experience.

HTML as a Markup Language: Its Function and PurposeHTML as a Markup Language: Its Function and PurposeApr 22, 2025 am 12:02 AM

The function of HTML is to define the structure and content of a web page, and its purpose is to provide a standardized way to display information. 1) HTML organizes various parts of the web page through tags and attributes, such as titles and paragraphs. 2) It supports the separation of content and performance and improves maintenance efficiency. 3) HTML is extensible, allowing custom tags to enhance SEO.

The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

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