Explore Topics

How to Center a DIV in CSS?

Last Updated : 18 Apr, 2025 - Asked By Ashok

Here is my HTML code. I want to center the id = 'outer_div' to the center of the page. How can I center a div in CSS?

html  css  centre alignment 

Answers
2024-01-30 12:42:56

To center a div in CSS, you can use the following code:

 

#outer_div {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

 

This code will center the outer_div element both horizontally and vertically on the page. The position: absolute; property is used to position the element relative to its parent container. The left: 50%; and top: 50%; properties are used to move the element to the center of the page. Finally, the transform: translate(-50%, -50%); property is used to adjust the position of the element so that it is perfectly centered.

2024-01-31 04:56:23

To center a <div> horizontally and vertically using CSS, you can use the following approach:

.center-div {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Position: absolute; positions the <div> relative to the nearest positioned ancestor or the initial containing block.top: 50%; and Left: 50%; position the top-left corner of the <div> at the center of its containing block

Transform: translate(-50%, -50%); Moves the <div> horizontally and vertically by -50% of its own width and height, respectively, effectively centering it both horizontally and vertically.

 

 

2024-02-09 11:22:11

We can do it by :

#outer_div{

display: flex;

align-items : center;

justify-content : center;

}

2024-03-18 16:28:38

#outer_div{

display :flex;

justify content :ceneter

align item : center

}

Your Answer



Other Resources

Quiz Image
Quiz

Test your knowledge with interactive quizzes.

Interview Questions Image
Interview Questions

Prepare for interviews with curated question sets.

Q&A Image
Q&A

Ask your coding-related doubts and get answers.

Certification Image
Certification

Earn certifications to enhance your resume.

internships Image
Internships

Hands-on projects to improve your skills.

Quiz Image
Quiz

Test your knowledge with interactive quizzes.

Interview Questions Image
Interview Questions

Prepare for interviews with curated question sets.

blog Image
Blogs

Add your technical blogs and read technical topics.

Certification Image
Certification

Earn certifications to enhance your resume.

Q&A Image
Q&A

Hands-on projects to improve your skills.