Reputation: 14783
I would like to center different images which are shown and hidden, depending on how the user clicks. What I did to center an image was:
img {
margin-left: auto;
margin-right: auto;
display: block;
}
which worked fine. But it does not work for a position: absolute;
Is there a css only way to center a position: absolute
div horizontally in the middle of body
or parent
without knowing the width
?
Upvotes: 0
Views: 282
Reputation: 9464
Give the element position: absolute
and position it 50% from the left
edge of the screen, then use transform: translate
to move it 50% of its width to the left.
HTML:
<div class="center"></div>
CSS:
.center {
position: absolute;
top: 0;
left: 50%;
transform: translateX(-50%);
}
Here's a pen with this.
Here's the browser support for 2d transforms, and information about which vendor prefixes you need.
You can also use transform: translate3d
to center elements vertically with the same logic. The CSS would then look like this:
.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate3d(-50%, -50%, 0);
}
Upvotes: 1
Reputation: 3106
The only way i know is using an additional div, like this:
HTML:
<div class="target">
<div class="wrapper"></div>
</div>
CSS:
.wrapper{
width:100px;
height:100px;
background:blue;
margin:0 auto;
margin-left:-50%;
}
.target{
position:absolute;
left:50%;
}
What this does is:
left:50%
on your main div
div
s contents in another wrapper div
element like shown in demo abovemargin-left:-50%
on the wrapper div
Upvotes: 0
Reputation: 63327
For absolutely positioned element, you can set the margin:auto
in combination with left:0
and right:0
(for horizontally centered) or top:0
and bottom:0
(for vertically centered):
img {
position:absolute;
left:0;
right:0;
margin:auto;
}
Upvotes: 5
Reputation: 1392
You can use:
padding-left: 50%;
margin-left: -(half the width of your image)px
It's not the cleanest solution it's probably not the right scenario for absolute positioning.
Upvotes: -1