Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

html
css
communitycreator

How to center an absolutely positioned element in CSS

Kedar Kodgire

Overview

Absolute positioning removes the HTML element from the normal document flow, and the document will reserve no space for that element in the document. The absolutely positioned element will be arranged according to the parent.

Centering the absolutely positioned element

Horizontal positioning

The absolutely positioned element can be horizontally centered using the following CSS properties and values.

  1. margin-left: auto;
  2. margin-right: auto;
  3. left: 0;
  4. right: 0;

Explanation

Applying these CSS properties to the image will provide a centered image. The margin-left and margin-right are set to auto, indicating that the browser will select the suitable margin. The left and right properties will place the positioned element in HTML horizontally.

In the CSS tab below:

  • Lines 11–14 shows the CSS properties discussed above to center the image.

Vertical positioning

Let's use the example above to center align the Educative image vertically. The absolutely positioned element will be vertically and horizontally centered using the following CSS properties and values.

  1. margin: auto
  2. left: 0
  3. right: 0
  4. top: 0
  5. bottom: 0

Note: The code above will center the block horizontally and vertically. To only vertically center the block

  1. Set margin-top and margin-bottom to auto.
  2. Set top and bottom to 0.

Explanation

We used margin property as it indicates margin to all the directions. The top and bottom properties will place the positioned element in HTML vertically.

In the CSS tab below:

  • Lines 11–15: Shows the code to center the image.

RELATED TAGS

html
css
communitycreator
RELATED COURSES

View all Courses

Keep Exploring