Home  >  Article  >  Web Front-end  >  How to center an image in a div with css

How to center an image in a div with css

下次还敢
下次还敢Original
2024-04-25 11:54:14652browse

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>

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>

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>

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>

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!

Statement:
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