Home > Web Front-end > CSS Tutorial > How to Center an Element Within Its Parent Div Using CSS?

How to Center an Element Within Its Parent Div Using CSS?

Susan Sarandon
Release: 2024-11-25 03:06:12
Original
980 people have browsed it

How to Center an Element Within Its Parent Div Using CSS?

Centering an Element Within a Parent

When centering an HTML element using left: 50%;, it aligns the element with the entire browser window. However, to center an element specifically within its parent

element, a different approach is needed.

To achieve this, assign text-align:center; to the parent

. This will center all content within the
, including the child element.

Next, add margin:auto; to the child element. This ensures that the child element is automatically adjusted within the parent

, regardless of its width or height.

Here's a demonstration using CSS:

#parent {
    text-align:center;
    background-color:blue;
    height:400px;
    width:600px;
}
.block {
    height:100px;
    width:200px;
    text-align:left;
}
.center {
    margin:auto;
    background-color:green;
}
Copy after login

Notice that margin:auto; centers the child element both horizontally and vertically within the parent

.

The above is the detailed content of How to Center an Element Within Its Parent Div Using 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template