Reputation: 3588
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.
Upvotes: 4
Views: 10252
Reputation: 11
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.
Upvotes: 1
Reputation: 705
.centered { position: fixed; top: 50%; left: 50%; margin-top: -[1/2(element-height)]; margin-left: -[1/2(element-width)];}
This work.
Upvotes: 0
Reputation: 76003
.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/
Upvotes: 7