Himmators
Himmators

Reputation: 15006

How do I center an absolute-positioned image with percentage width?

I have an image with the following css:

element.style {
    right: 50%;
    margin-right: -220px;
    top: 31%;
    width: 440px;
    position: absolute;
}

I need to change it so that the width is set in percent instead(35.4%). Can I still center it and keep position absolute?

Upvotes: 0

Views: 1635

Answers (2)

Danield
Danield

Reputation: 125443

You can horizontally center using

left:0; right:0; margin:auto;

So if you have a div as markup, css would be

div
{
    top: 31%;
    width: 38%;
    height: 100px;
    position: absolute;
    left:0;right:0;
    margin: auto;
}

FIDDLE

As long as you have defined a width (in px or % - it doesn't matter) this will work

Upvotes: 0

Marcel Gwerder
Marcel Gwerder

Reputation: 8520

Of course, if you want it the same way as above just use 35.4/2 = 17.7 as your margin (DEMO):

element.style {
    right: 50%;
    margin-right: -17.7%;
    top: 31%;
    width: 35.4%;
    position: absolute;
}

Upvotes: 1

Related Questions