How to set the image position to center in css

王林
Release: 2023-01-03 09:26:24
Original
5372 people have browsed it
How to center the image in css: You can add a p tag outside the image, and then center the image by setting the line-height attribute, such as [

How to set the image position to center in css p> line-height:300px;].

How to set the image position to center in css

The operating environment of this article: windows10 system, css 3, thinkpad t480 computer.

The specific method is as follows:

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

html code is as follows:

<div class="img_wrap">
   <img  src="wgs.jpg" alt="How to set the image position to center in css" >
</div>
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

The effect is as follows:

How to set the image position to center in css

2. Use the background method:

The html code is as follows:

<div class="img_wrap"></div>
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:

How to set the image position to center in css

(Learning video sharing: css video tutorial)

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

html code is as follows:

 <div class="img_wrap">
     <p><img  src="wgs.jpg" alt="How to set the image position to center in css" ></p>
 </div>
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

Effect The picture is as follows:

How to set the image position to center in css

Related recommendations: CSS tutorial

The above is the detailed content of How to set the image position to center in css. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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