Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: center a fixed div

I have a class for a fixed positioned div to stay at the bottom of the view port. I am trying to make the width automatic so that as the div changes width, it remains centered.

.box {
position: fixed;
width: 80%;
bottom: 20px;
left: 50%;
margin: 0 0 0 -40%;
max-height: 50%;
overflow: auto
}

Any ideas? I tried a container with text-align: center then display: inline, but it produced crazy results.

like image 843
Myforwik Avatar asked Oct 29 '25 01:10

Myforwik


2 Answers

.box {
    position   : fixed;
    left       : 10%;
    right      : 10%;
    bottom     : 20px;
    max-height : 50%;
    overflow   : auto;
}

You can use left and right together to center the element (instead of using width).

If you want to use width then you can do this:

.box {
    position   : fixed;
    left       : 10%;
    width      : 80%;
    bottom     : 20px;
    max-height : 50%;
    overflow   : auto;
}

If you want to center HTML inside the fixed element you can do this:

.box > div {
    width      : 50%;
    min-width  : 150px;
    margin     : 0 auto;
    text-align : center;
}

Here is a demo: http://jsfiddle.net/dFXt5/

like image 173
Jasper Avatar answered Oct 30 '25 17:10

Jasper


By playing around I came across a solution that works:

align-items: center;
display: flex;
width: fit-content;
left: 0;
right: 0;
margin-inline: auto;
justify-content: center;
position: fixed;
z-index: 1000;

left: 0 and right: 0:

These ensure the alert spans horizontally across the viewport, but combined with width: fit-content, the actual width is only as large as the content. margin-inline: auto:

Centers the alert horizontally by automatically balancing the space on both sides. display: flex; align-items: center; justify-content: center;:

Ensures that the content inside the alert is properly aligned and centered vertically and horizontally. position: fixed:

Keeps the alert fixed in the viewport regardless of scrolling.

like image 42
Zanoni The 1st Avatar answered Oct 30 '25 16:10

Zanoni The 1st