Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • CSS Tutorial
  • CSS Exercises
  • CSS Interview Questions
  • CSS Selectors
  • CSS Properties
  • CSS Functions
  • CSS Examples
  • CSS Cheat Sheet
  • CSS Templates
  • CSS Frameworks
  • Bootstrap
  • Tailwind
  • CSS Formatter
Open In App
Next Article:
CSS Background
Next article icon

CSS | Centering Elements

Last Updated : 20 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes we face problems with centering an element in a web page. Is it really so hard? It is not too difficult to center an element. There so many different ways of doing it. 
One thing we need to know is that, which technique is for which purpose. Once you understand the problem, picking up the best technique will be much easier. 
So let us see some situation and discuss the best method to achieve the goal. 
 

  • Horizontally 
    • Inline elements 
      We can easily center an inline element within a block level element like this: 
css
                    // Aligning text in center                     .center                     {                          text-align: center;                     }                      
  • Block level elements 
    We can center a block-level element by giving it margin-left and margin-right of auto (which has a known specified width): 
     
css
                    // Aligning an element of defined length in center                     // Remember to define the width of the element otherwise it                      //will be full width and 'auto' will not work                     .center                      {                         margin: 0 auto;                         width: 200px;                     }                       
  • More than one block level elements 
    If we have two or more block-level elements that need to be centered horizontally in a row, it can be better served making them a different display type display: inline-block; 
     
css
                                 .parent                 {                   // Aligning the child of this parent in center                   text-align: center;                 }                 .child                 {                   // set the display of child elements                    display: inline-block;                   text-align: left;                 }                  
  • Vertically 
    • Inline elements 
      We can easily center an inline element within a block level element like this: 
       
css
                           // Set the display of the parent class as table                         .parent                         {                           display: table;                           height: 250px;                           background: white;                           width: 240px;                           margin: 20px;                         }                          // Set the display of the child class as table-cell                         .child                         {                           display: table-cell;                           margin: 0;                           background: black;                           color: white;                           padding: 20px;                           border: 10px solid white;                           vertical-align: middle;                         }                      
  • Block level elements of known height 
    We can easily center an inline element within a block level element like this: 
     
css
                            // Set the position of the parent as relative to other                                   .parent                          {                           position: relative;                         }                          // Set position of the child as absolute in its parent class                         // so that it can be placed anywhere in the parent class                         .child                          {                           position: absolute;                           top: 50%;                           height: 100px;                            /* responsible for padding and border                            if not using box-sizing: border-box; */                           margin-top: -50px;                          }                      
  • Block level elements of unknown height 
    We can easily center an inline element within a block level element like this: 
     
css
                           // Set position of child as absolute in its parent class                                    .parent                          {                           position: relative;                         }                          // Set top of the child 50% of viewport                         // Translate the child by 50% of its height about                               // negative y axis                         .child                          {                           position: absolute;                           top: 50%;                           transform: translateY(-50%);                         }                      
  • Both Horizontally & Vertically 
    • Element with fixed height and width 
      Using negative margins equal to half of that width and height, after you've absolutely positioned it at 50% / 50% will center it. 
css
                    // Set position of parent class as relative                     .parent                      {                       position: relative;                     }                      // Set top and left of an element of                     // known height as 50%                     .child                      {                       width: 300px;                       height: 100px;                       padding: 20px;                        position: absolute;                       top: 50%;                       left: 50%;                        margin: -70px 0 0 -170px;                     }                       
  • Element with unknown height and width 
    When we don't know the width or height, we can use the transform property and a negative translate of 50% in both directions to center: 
css
                    // Set position of parent as relative to other                     .parent                      {                       position: relative;                     }                      // Set top and left of an element of                      // known height as 50%. Translate the                     // element 50% of its height and width                       // about negative x-axis and negative y-axis                     .child                      {                       position: absolute;                       top: 50%; //                        left: 50%;                       transform: translate(-50%, -50%);                     }                       


Note: The '.' operator is used in CSS to identify a CSS class. In the above examples, the class parent is used to style the parent element and the class child is used for the child element.


Next Article
CSS Background

S

Saptarshi_Das
Improve
Article Tags :
  • Web Technologies
  • CSS
  • CSS-Basics

Similar Reads

    CSS Introduction
    CSS (Cascading Style Sheets) is a language designed to simplify the process of making web pages presentable.It allows you to apply styles to HTML documents by prescribing colors, fonts, spacing, and positioning.The main advantages are the separation of content (in HTML) and styling (in CSS) and the
    4 min read
    Types of CSS (Cascading Style Sheet)
    CSS is used to style and layout web pages, controlling the appearance of HTML elements. It allows developers to create visually appealing designs and ensure a consistent look across a website.Types of CSSCSS can be implemented in three different ways:Inline CSSInternal or Embedded CSSExternal CSS1.
    3 min read
    CSS | Centering Elements
    Sometimes we face problems with centering an element in a web page. Is it really so hard? It is not too difficult to center an element. There so many different ways of doing it. One thing we need to know is that, which technique is for which purpose. Once you understand the problem, picking up the b
    4 min read
    CSS Background
    The CSS background is the area behind an element's content, which can be a color, image, or both. The background property lets you control these aspects, including color, image, position, and repetition.You can try different types of background here- iframe { width: 100%; height:410px;} @media (min-
    5 min read
    CSS Positioning Elements
    CSS positioning defines how elements are placed within a web page. It allows you to control the layout, stacking order, and alignment of elements. The primary positioning types in CSS are:Position PropertyDescriptionFixedAn element with position: fixed property remains in the same position relative
    4 min read
    CSS Borders
    Borders in CSS are used to create a visible outline around an element. They can be customized in terms ofWidth: The thickness of the border.Style: The appearance of the border (solid, dashed, dotted, etc.).Color: The color of the border.You can try different types of borders here- #custom-iframe{ he
    5 min read
    CSS Margins
    CSS margins are used to create space around an element, separating it from neighboring elements and the edges of the webpage. They control the layout by adjusting the distance between elements, providing better organization and readability.Syntax:body { margin: value;}HTML<html> <head>
    4 min read
    CSS Text Formatting
    CSS Text Formatting plays a crucial role in web design, allowing developers to control the visual presentation of text elements. Nearly 70% of a webpage's content is text, making effective formatting essential for readability and user engagement. CSS lets you adjust font properties, text alignment,
    8 min read
    CSS Float
    The CSS float property is used to move an element out of the normal document flow and position it to the left or right of its container. For example, float: left moves the element to the left, and float: right moves it to the right. Other content will wrap around the floated element which helps to c
    3 min read
    CSS Lists
    CSS Lists are used to display items in a clear and organized manner, either with bullets (unordered) or numbers (ordered). They help keep content neat and structured on a webpage. With CSS, you can customize the look of lists to improve the design and layout of your content. Try It: .custom-item { b
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences