Home >Web Front-end >CSS Tutorial >How Do I Center an Image Horizontally and Vertically within a Div?

How Do I Center an Image Horizontally and Vertically within a Div?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-03 07:46:10626browse

How Do I Center an Image Horizontally and Vertically within a Div?

Positioning an Image Centrally within a Div

You desire to position an image in a div such that it resides exactly in the middle and center. To achieve this alignment, follow these steps:

1. Create the Div with Absolute Positioning:

<div>

2. Configure Image Properties:

#over img {
  margin-left: auto;
  margin-right: auto;
  display: block;
}
  • margin-left: auto;: This ensures the image is positioned to the right edge of the div.
  • margin-right: auto;: Simultaneously positions the right edge of the image to the left edge of the div.
  • display: block;: Converts the image into a block-level element, allowing for vertical centering.

Example:

<div>

This approach aligns the image centrally within the div, regardless of the div's size.

The above is the detailed content of How Do I Center an Image Horizontally and Vertically within a Div?. 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