How to center an image in a div with css

下次还敢
Release: 2024-04-25 11:54:14
Original
701 people have browsed it

The methods in CSS to center images in divs are: Text alignment: suitable for vertical centering of images and text. Flexbox: Suitable for horizontal and vertical centering of images. Conversion: works for fixed size images. Automatic margins: suitable for situations where the width of the image is known.

How to center an image in a div with css

How to center the image in the div in CSS

Method 1: text-align

<code class="css">div {
  text-align: center;
}

img {
  display: inline-block;
}</code>
Copy after login

This method is suitable for situations where you want the image to be vertically centered together with the text.

Method 2: flexbox

<code class="css">div {
  display: flex;
  justify-content: center;
  align-items: center;
}

img {
  max-width: 100%;
}</code>
Copy after login

flexbox allows flexible layout. This method is suitable for situations where pictures need to be centered horizontally and vertically.

Method 3: transform

<code class="css">div {
  position: relative;
}

img {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}</code>
Copy after login

This method uses absolute positioning and transform and is suitable for fixed-size images.

Method 4: margin auto

<code class="css">div {
  text-align: center;
}

img {
  margin: auto;
}</code>
Copy after login

margin: auto automatically centers the image, but can only be used when the image width is known.

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

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!