Matt Bowyer Matt Bowyer - 1 month ago 16
CSS Question

Absolutely-positioned, variable-width, centred HMTL 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?

Answer

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%)).

Comments