Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Gareth Redfern
Gareth Redfern
36,217 Points

Centre Align An Absolute Positioned Element With Unknown Width

Does anyone have a good solution for this? I came across this article but it doesn't work for me. I have created a Codepen and can get it to work if the element is relatively positioned but not if it is absolute positioned.

2 Answers

This always works for me.

.absolute-center {
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
}
Gareth Redfern
Gareth Redfern
36,217 Points

That worked great thank you one to bookmark :)

afaik this will only work if the element has a known width

Kevin Korte
Kevin Korte
28,148 Points

There are some negative consequences when absolute children. Another solution would be to use some Javascript or jQuery to calculate and set some of the positioning elements so it would be more dynamic to whatever content was inside the absolute positioned element.

I tried to replicate it as close as possible.

http://codepen.io/kevink/pen/yhkJd?editors=110