-2

I have a snackbar message pop up when there is a successful patch or post in my application. These messages can be short or long sometimes based on the context of the object being updated.

This originally was set to left: 50% however I changed it because sometimes the message way not centered correctly. How can I make this snackbar always centered no matter how long the text is?

#snackbar {
     visibility: hidden;
     min-width: 250px;
     margin-left: -125px;
     background-color: $apple;
     color: #fff;
     text-align: center;
     border-radius: 5px;
     padding: 16px;
     position: fixed;
     z-index: 1;
     left: 40%;
     bottom: 30px;
 }

HTML is as follows

<body>
    <%= render "shared/sidenav" if current_user %>
    <div id=<%= "#{'main' if current_user}" %>>
      <% flash.each do |name, msg| %>
        <%= content_tag :div, msg, class: "alert alert-#{name}", id: 'alert' %>
      <% end %>
      <%= yield %>
      <div id="snackbar"></div>
    </div>
  </body>

Snackbar is visible upon an HTTP request.

enter image description here

Trenton T
  • 75
  • 9

1 Answers1

2

You can use a combination of left: 50% and transform: translateX(-50%) for this:

#snackbar {
  position: fixed;
  min-width: 250px;
  background-color: green;
  color: #fff;
  text-align: center;
  border-radius: 5px;
  padding: 16px;
  z-index: 1;
  left: 50%;
  transform: translateX(-50%);
  bottom: 30px;
}
<div id="snackbar">
  <p>Eleifend nec eget. Id massa quis eu vitae elit. Bibendum interdum semper. Donec libero duis.</p>
</div>

Small Example

#snackbar {
  position: fixed;
  min-width: 250px;
  background-color: green;
  color: #fff;
  text-align: center;
  border-radius: 5px;
  padding: 16px;
  z-index: 1;
  left: 50%;
  transform: translateX(-50%);
  bottom: 30px;
}
<div id="snackbar">
  <p>Eleifend nec eget.</p>
</div>

left is based off of the left side of the box. Translate is based on the width of the box, so this essentially moves the left edge of the box to the middle of the element's parent and then brings it back 50 percent of the box width.

disinfor
  • 10,865
  • 2
  • 33
  • 44