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
Susan SarandonOriginal
2024-11-25 03:06:12981browse

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;
}

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!

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