- This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
Viewing 3 posts - 1 through 3 (of 3 total)
- The forum ‘CSS’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
I’ve seen (and used) a lot of examples of centering absolute positioning by using this method:
position: absolute;
left: 50%;
margin-left: -100px; (half the element width))
width: 100%;
the obvious problem is in knowing the width of the element, which won’t work for dynamic-width elements.
Recently, I started playing with using -33% left margin instead and this seems to center pretty well. Has anybody else tried this and/or see a problem with it?
There is a CSS3 alternative to
margin-left: /* (half the element width) */
It’s
transform:translateX(-50%);
If you need vertical center you can use transformY(-50%)
in conjunction withtop:50%
.
Here’s a codepen where I use both combined into a single property
transform:translate(-50%, -50%);
http://codepen.io/Paulie-D/pen/BGkcr
Support – http://caniuse.com/transforms2d
Hi,
You can center align a div horizontally and vertically by writing this code in css:
#nameofdiv
{Position: absolute;
Left: 0;
Right; 0;
Bottom: 0;
Top: 0;
text-align: center;
line-height: 50px;
}
Hope this will resolve your problem.