0

I have this :

#toast {
  position: fixed;
  left: 0;
  right: 0;
  margin: auto;
  bottom: 20px;
  width: auto;/* not needed */
  max-width: 90vw;
  min-width: 250px;
  font-size: 16px;
  background: red;/* for refrence */
}
<div id="toast">Hi</div>

I want my element 250px wide, but instead it is 90vw. (250px can be 50px, still problems) Why is it 90vw, and how do I make it 250px when it has no content? It should still be centered. transform: translateX(-50%) doesn't work because then it won't be wider than 50vw.

Rainbow
  • 6,772
  • 3
  • 11
  • 28
Milina
  • 3
  • 4

2 Answers2

2

Because when you set left and right at the same time, combined with width:auto (the default), the element's width will be calculated to "fill in the offsets" - you're effectively setting 100% width here.

Remove the right:0 (or left) and the width is what you'd expect:

#toast {
  background-color: pink;
  position: fixed;
  left: 0;
  //right: 0;
  margin: auto;
  bottom: 20px;
  width: auto;
  max-width: 90vw;
  min-width: 250px;
  font-size: 16px;
}
<div id="toast">Hi</div>

To center your element, one pretty easy way would be to set display:flex on the body, because when you apply auto margins to a flex item, that item will automatically extend its specified margin to occupy the extra space in the flex container:

body {
 display:flex;
}

#toast {
  background-color: pink;
  margin: auto;
  max-width: 90vw;
  min-width: 250px;
  font-size: 16px;
}
<div id="toast">Hi</div>
Scott Weaver
  • 7,192
  • 2
  • 31
  • 43
1

Adding to what @Sweaver2112 Said, Because margins don't apply on absolute/fixed positioning, To center it you can try something like this.

*, *:before, *:after {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.parent {
  background-color: brown;
  text-align: center;
  position: fixed;
  bottom:0;
}

.toast {
  /* To remove center being inherited  */
  text-align: initial;
  /* Inline level elements get moved by text-align property of their parent */
  display: inline-block;
  max-width: 90vw;
  min-width: 250px;
  background: orange; 
}
<div class="parent">
  <div class="toast">
    <h3>Triggering the min-width </h3>
  </div>
  <div class="toast">
    <h3>Triggering the max-width </h3>
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
    in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
</div>
Rainbow
  • 6,772
  • 3
  • 11
  • 28