In two minutes, you will learn three ways to center an image in CSS.

烟雨青岚
Release: 2020-07-09 17:20:20
forward
3480 people have browsed it

In two minutes, you will learn three ways to center an image in CSS.

When beautifying web pages, you will always use image centering. Do you know what are the three ways to center images in CSS? Let’s take a look below.

1. Use display:table-cell, the specific code is as follows:

html code is as follows:

  
Copy after login

css code is as follows:

.img_wrap{
     width: 400px;
     height: 300px;
     border: 1px dashed #ccc;
     display: table-cell; //主要是这个属性
    vertical-align: middle;
     text-align: center;
 }效果如下:
Copy after login

2. Use background method:

html code is as follows:

 

Copy after login

css code is as follows:

.img_wrap{
    width: 400px;
    height: 300px;
    border: 1px dashed #ccc;
    background: url(wgs.jpg) no-repeat center center;
}
Copy after login

The effect is as shown below:

3. Use a p tag outside the picture, and set the line-height to center the picture vertically:

The html code is as follows:

Copy after login

css code is as follows:

*{margin: 0px;padding: 0px}
.img_wrap{
    width: 400px;
    height: 300px;
    border: 1px dashed #ccc;
    text-align: center;}
.img_wrap p{
    width:400px;
    height:300px;
    line-height:300px;  /* 行高等于高度 */
 }
.img_wrap p img{
    *margin-top:expression((400 - this.height )/2);  /* CSS表达式用来兼容IE6/IE7 */
    vertical-align:middle;
    border:1px solid #ccc;
 }
Copy after login

The rendering is as follows:

Thank you for reading, I hope you will benefit a lot

Recommended tutorial: "CSS Tutorial"

The above is the detailed content of In two minutes, you will learn three ways to center an image in CSS.. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
css
source:csdn.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!