Home >Web Front-end >CSS Tutorial >How to center a div in css to display an image
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;".
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;}
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>
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; }
(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!