Table of Contents
Solve the problem?? Center the image horizontally and vertically
3. display:table simulates a table to achieve vertical centering of images
4 , jQuery method to achieve image centering
Home Web Front-end HTML Tutorial CSS to make pictures horizontally and vertically centered_html/css_WEB-ITnose

CSS to make pictures horizontally and vertically centered_html/css_WEB-ITnose

Jun 24, 2016 am 11:51 AM

The so-called horizontal and vertical centering of the image means placing the image in a container element (the container is larger than the image size or a container with a specified size), and the image is located in the middle of the container (the middle refers to in the middle of the element container), and the image is not displayed in the form of a background-image (background-image), but in the form of an element. As shown in the figure below:

Solve the problem?? Center the image horizontally and vertically

It is quite easy to solve the horizontal centering, if the image floats left and "display:inline" At this time, we only need to set a "text-align:center" attribute for the image to successfully solve the horizontal centering problem.

For the best solution for vertical centering, in modern browsers, we can set "dipslay:table-cell;vertical-align:middle" for the image container. This method can smoothly achieve the image Vertically centered, but only works in modern browsers and does not work properly in IE6-7. Will this be impossible to achieve? Don’t worry, everyone, let’s take a look at the following methods:

1. table-cell plus display:inline

This method is amazing, as we mentioned earlier I have said that using display-table and vertical-middle is the best way to achieve vertical centering of images in modern browsers, but IE6-7 does not support display:table-cell. In fact, it is not that serious. We only need to use IE6-7 to Give him another way to write it. In fact, it is not difficult to implement it under IE after mastering the principle. Let's take a look at this idea first:

  1. First, set "display:table-cell;vertical-" in the container element of the image. align:middle;" to achieve vertical centering of the current browser;
  2. IE6-7 has a good method, which is to create a line box with the same height as the image container, and give this line The box also sets "vertical-align:middle".

The next key is to create a line box for IE6-7. Fortunately, IE6-7 partially supports "dipslay:inline-block". In this way, we can create an empty element (such as span) in the image container and set the span's "display:inline-block;height:100%;vertical-align:middle".

There is a detail that needs to be paid attention to when creating a line box. The width of the empty line-block element in IE6-7 is "0", which has no effect in IE6-7. At this time, we need to add span If "width:1px" is selected, it will cause a 1px error in horizontal centering, but you can accept this bug.

Then the final solution is to use display:table-cell and set the display:inline-block line span. Of course, you still need to write some special code for IE. Next, let’s look at the code:

HTML Markup

<ul class="imgWrap clearfix">                <li><a href="#" class="imgBox"><span></span><img src="images/img1.jpg" alt="" /></a></li>                <li><a href="#" class="imgBox"><span></span><img src="images/img2.jpg" alt="" /></a></li>                <li><a href="#" class="imgBox"><span></span><img src="images/img3.jpg" alt="" /></a></li>                <li><a href="#" class="imgBox"><span></span><img src="images/img4.jpg" alt="" /></a></li>            </ul>        
Copy after login

<style type="text/css">                .imgWrap li {                    float: left;                    border: solid 1px #666;                    margin: 10px 10px 0 0;                    list-style: none;                    border-collapse: collapse;                 }                .imgWrap a {                    background: #ffa url(images/gridBg.gif) repeat center;                    width: 219px;                    height: 219px;                    display: table-cell;/*图片容器以表格的单元格形式显示*/                    text-align: center; /* 实现水平居中 */                    vertical-align: middle; /*实现垂直居中*/                                    }                .imgWrap a:hover {                    background-color: #dfd;                }                .imgWrap img {                    border: solid 1px #66f;                    vertical-align: middle; /*图片垂直居中*/                }                </style>                <!--下面是解决IE6-7的正常显示的代码-->                <!--[if lt IE 8]>                    <style type="text/css">                    .imgWrap a {                        display: block;                    }                    .imgWrap span {                        display: inline-block;                        vertical-align: middle;                        height: 100%;                    }                    .imgWrap {                        _height: 0;                        zoom: 1;                    }                    </style>                <![endif]-->
Copy after login

2. Use a blank label to vertically center the image

Set the span inline element to For inline block elements, that is, set its display to "inline-block", position its width to 1px, and its height to 100% of the container, so that the height can be the same as the height of the container, and then set it through "vertical-align:middle" Align vertically to achieve the desired effect. I feel that this method is better than the above method. The most important thing is not to write effects for IE alone, and it is easy to understand

<ul class="imgWrap clearfix">                <li><a href="#" class="imgBox"><span></span><img src="images/img1.jpg" alt="" /></a></li>                <li><a href="#" class="imgBox"><span></span><img src="images/img2.jpg" alt="" /></a></li>                <li><a href="#" class="imgBox"><span></span><img src="images/img3.jpg" alt="" /></a></li>                <li><a href="#" class="imgBox"><span></span><img src="images/img4.jpg" alt="" /></a></li>            </ul>
Copy after login

<style type="text/css">                .imgWrap li{                     width: 219px;                    height: 219px;                    float: left;                    border: solid 1px #666;                    margin: 10px 10px 0 0;                    list-style: none;                    text-align: center;                    font-size: 0;                }                .imgWrap a {                    display: block;                    height: 100%;                    background: #ffa url(images/gridBg.gif) repeat center;                }                .imgWrap a:hover {                    background-color: green;                }                .imgWrap span {                    display: inline-block;/*将行内元素改变为行内块元素显示*/                    width: 1px;/*实现IE下可读效果*/                    height: 100%;/*使用元素高度和图片容器高度一样*/                    vertical-align: middle;/*垂直对齐*/                }                .imgWrap img {                    vertical-align: middle;                }            </style>
Copy after login

3. display:table simulates a table to achieve vertical centering of images

The method I will talk about next is a bit complicated in structure, and it needs to be implemented with hacks in IE6-7. This method is to simulate the form of a table to achieve the effect of vertical centering of the image.

Everyone knows that tables have rows (table-row) and cells (table-cell). As we all know, "vertical-align: middle" in table cells can center elements vertically, so the following example It is made using this principle. Let’s look at the code together

<ul class="imgWrap clearfix">                <li>                    <div class="table">                        <div class="tableCell">                            <a href="#" class="imgBox"><img src="images/img1.jpg" alt="" /></a>                        </div>                    </div>                    </li>                <li>                    <div class="table">                        <div class="tableCell">                            <a href="#" class="imgBox"><img src="images/img2.jpg" alt="" /></a>                        </div>                    </div>                    </li>                <li>                    <div class="table">                        <div class="tableCell">                            <a href="#" class="imgBox"><img src="images/img3.jpg" alt="" /></a>                        </div>                    </div>                    </li>                <li>                    <div class="table">                        <div class="tableCell">                            <a href="#" class="imgBox"><img src="images/img4.jpg" alt="" /></a>                        </div>                    </div>                    </li>            </ul>    
Copy after login

.imgWrap li {                background: #ffa url(images/gridBg.gif) repeat center;                width: 219px;                height: 219px;                float: left;                border: solid 1px #666;                margin: 10px 10px 0 0;                list-style: none;                text-align: center;            }            .table {                width: 100%;                height: 100%;                display: table;                position: relative;            }                    .tableCell {                                display: table-cell;                vertical-align: middle;                text-align: center;                            padding: 10px;                *position: absolute;                *top: 50%;                *left: 50%;            }            .imgWrap a {                display: block;                *position:relative;                *top: -50%;                *left: -50%;            }
Copy after login

4 , jQuery method to achieve image centering

This method is very simple, that is, you have to use the jQuery method to convert the image to the background image of its parent element, and display the background image in the center of its parent element, and then add itself Set the transparency to "0", which can also achieve the effect of centering the image.

Html Markup

            <ul class="imgWrap clearfix">                <li><a href="#" class="imgBox"><img src="images/img1.jpg" alt="" /></a></li>                <li><a href="#" class="imgBox"><img src="images/img2.jpg" alt="" /></a></li>                <li><a href="#" class="imgBox"><img src="images/img3.jpg" alt="" /></a></li>                <li><a href="#" class="imgBox"><img src="images/img4.jpg" alt="" /></a></li>            </ul>    
Copy after login

CSS Code

            .imgWrap li {                float: left;                border: solid 1px #666;                margin: 10px 10px 0 0;                list-style: none;                background: #ffa url(images/gridBg.gif) repeat center;            }            .imgWrap a {                width: 219px;                height: 219px;                display: block;            }
Copy after login

jQuery Code

            //先写一个小插件            $.fn.imgVAlign=function(){                return $(this).each(function(i){                    //获取图片的src值,并定义给变量bg                    var bg = $(this).attr("src");                    //给图片的父元素定义背景图片的样式,并且背景图片                    $(this).parent().css({"background": "url("+ bg +") no-repeat center center"                    });                    //将图片隐藏                    $(this).css("opacity","0");                });            }            //调用上面写的插件            $(document).ready(function(){                $(".imgBox img").imgVAlign();            });
Copy after login

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

What is the purpose of the <progress> element? What is the purpose of the <progress> element? Mar 21, 2025 pm 12:34 PM

The article discusses the HTML &lt;progress&gt; element, its purpose, styling, and differences from the &lt;meter&gt; element. The main focus is on using &lt;progress&gt; for task completion and &lt;meter&gt; for stati

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

What is the purpose of the <datalist> element? What is the purpose of the <datalist> element? Mar 21, 2025 pm 12:33 PM

The article discusses the HTML &lt;datalist&gt; element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the purpose of the <meter> element? What is the purpose of the <meter> element? Mar 21, 2025 pm 12:35 PM

The article discusses the HTML &lt;meter&gt; element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates &lt;meter&gt; from &lt;progress&gt; and ex

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

What is an example of a starting tag in HTML? What is an example of a starting tag in HTML? Apr 06, 2025 am 12:04 AM

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Apr 04, 2025 pm 11:54 PM

GiteePages static website deployment failed: 404 error troubleshooting and resolution when using Gitee...

See all articles