overlap notification badge on glyph in Bootstrap 3

2020-05-11 10:53发布

问题:

I'm trying to create a comment/notification setup in bootstrap, and can't seem to get the alignment right.

I'm going for a pretty common layout as in this screenshot:

...but I can't get it to lignup. Here's a Bootply of my attempt.

HTML:

<div class="container">
  <button class="btn btn-default btn-lg btn-link" style="font-size:36px;">
    <span class="glyphicon glyphicon-comment"></span>
  </button>
  <span class="badge badge-notify">3</span>
</div>

CSS:

.badge-notify{
   background:red;
   position:absolute;
   top:0px;
  }

回答1:

Try this:

/* CSS used here will be applied after bootstrap.css */
.badge-notify{
   background:red;
   position:relative;
   top: -20px;
   left: -35px;
}


<div class="container">
  <button class="btn btn-default btn-lg btn-link" style="font-size:36px;">
    <span class="glyphicon glyphicon-comment"></span>
  </button>
  <span class="badge badge-notify">3</span>
</div>

Bootply: http://www.bootply.com/7teIvGLIzY



回答2:

I'm sharing the point of view that transform is a better way to do this task. However, I offer you these snippets to make this approach work:

    <div class="container">
      <button class="btn btn-default btn-lg btn-link" style="font-size:36px;">
        <span class="glyphicon glyphicon-comment"></span>
      </button>
      <span class="badge badge-notify">3</span>
    </div>

   .badge-notify{
     background:red;
     position:relative;
     -moz-transform: translate(-100%, -100%); /* For Firefox */
     -ms-transform: translate(-100%, -100%); /* for IE */
     -webkit-transform: translate(-100%, -100%); /* For Safari, Chrome, iOS */
     -o-transform: translate(-100%, -100%); /* For Opera */

Tip: it might be useful to play with percentage values inside translate's brackets for the best result. Moreover, you can try using many other effects like 3D, rotating and so on.



回答3:

For dynamism, I'd like to mention the usage of transform instead of relying on trial/error of pixels (which might still be of your use, depending on the use case)

<div class="container">
  <button class="btn btn-default btn-lg btn-link" style="font-size:36px;">
    <span class="glyphicon glyphicon-comment"></span>
  </button>
  <span class="badge badge-notify">3</span>
</div>

.badge-notify{
   background:red;
   position:relative;
   transform: (-100%, -100%);
}

This will position the badge just touching to the button. Depending on how much overlapping you want, decrease the x value. eg., for half of the badge - transform: (-150%, -100%) would be ideal.