Matt Bowyer
Matt Bowyer

Reputation: 215

Absolutely-positioned, variable-width, centred HTML element

I am trying to make a pop-up lightbox on my page which shrinks to fit the size of the element inside it, and centre it on the page. So far I have:

.lightboxVariable{
    display:block;
    position: absolute;
    top:0;
    bottom: 0;
    width : auto;
    left:0;
    right:0;
    padding-left:10px;    
    padding-right:20px;
    padding-top:10px;
    padding-bottom:20px;
    background:rgba(255,255,255,0.9);
    border:black, thin;
    box-shadow: 5px 5px 5px grey;
    z-index:1000000;
    overflow: auto;
    text-align:center;
    height:800px;
    }

Now with the left:0; and right:0;, the element spreads across the entire page (ie it ignores the width:auto;) but without them, the element just sits against the left-hand side of the page.

Is there a way to do both without having to resort to some sort of js-based code?

Upvotes: 0

Views: 48

Answers (1)

Davey
Davey

Reputation: 2514

You could try the following

width: auto;
height: auto;
top: 50%;
left: 50%;
// don't declare right or bottom
transform: translateX(-50%) translateY(-50%);

It will put the left edge of the element in the center (left: 50%;), then nudge it back to the left (translateX(-50%)).

Similarly for vertical center (top: 50%;) and (translateY(-50%)).

Upvotes: 1

Related Questions