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
Release: 2024-12-03 07:46:10
Original
622 people have browsed it

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>
Copy after login
Copy after login

2. Configure Image Properties:

#over img {
  margin-left: auto;
  margin-right: auto;
  display: block;
}
Copy after login
  • 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>
Copy after login
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template