How to center a div in css to display an image

藏色散人
Release: 2023-02-17 18:11:01
Original
9821 people have browsed it

Css method to center a div to display an image: 1. Use the margin attribute of the image to center the image horizontally, code such as "margin:0 auto;"; 2. Use the padding attribute of the div to center the image vertically, the code Such as "padding-top:50px;".

How to center a div in css to display an image

The operating environment of this tutorial: Windows 7 system, Dell G3 computer, HTML5&&CSS3 version.

How to center the image in a div using css?

How to center the image in the div

Use the margin attribute of the image to center the image horizontally, and use the padding attribute of the div to center the image vertically.

The structure code is the same as above;

css code is as follows:

div {
width:300px;
height:150px; 
background-color:#eee; 
padding-top:50px; 
border:#000 1px solid;
}
 
img {display:block; margin:0 auto;}
Copy after login

Note:

img is an inline element, and its margin attribute must be set to center it. It is necessary to convert it into a block element display:block; and then use margin:0 auto; to achieve horizontal centering of the image; (Some designers add a div tag to the image, and then use the margin of the div tag to achieve centering

Idea: Use the text-align attribute to center the image horizontally, and then set the value of padding-top to center it vertically.

The structure is as follows:

<style type="text/css">
 div{
  width:180px;
  height:180px;
  border:1px solid #000;
  position:relative;
  display:table-cell;
  text-align:center;
  vertical-align:middle;
 }
 div p{
  position:static;
  +position:absolute;
  top:50%;
 }
 div img{
  position:static;
  +position:relative;
  top:-50%;
  left:-50%;
 }
 </style>
 
<div><p><img src="0225/12986229678396.jpg" width="120" height="120"></p></div><br>
<div><p><img src="0225/12986229678396.jpg" width="160" height="160"></p></div>
Copy after login

Method 2

<div>
<img src="images/tt.gif" width="150" height="100" />
</div>
css样式如下:
div {
width:300px; 
height:150px;
background-color:#ccc; 
border:#000 1px solid; 
text-align:center; 
padding-top:50px;
}
Copy after login

(Recommended: css video tutorial)

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

Related labels:
css
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