うまとま君の技術めも

2015年新卒入社した社畜の勉強内容などなど

.btn-groupにtooltipを使うとデザインがズレる

環境

.btn-groupにtooltipを使うとデザインがズレる

.btn-group内のbuttontooltipを使用すると、 tooltipが発動した時に1px程度ズレが生じてしまいます。

f:id:umatomakun:20150321171659g:plain

<div class="btn-group" role="group">
    <button
        type="button"
        class="btn btn-default"
        data-toggle="tooltip"
        title="Tooltip">
        Left
    </button>
    <button type="button" class="btn btn-default">Middle</button>
    <button type="button" class="btn btn-default">Right</button>
</div>

何故ズレが生じているのか?

Bootstrapのソースコードを見てみると、隣接している.btnmargin-left: -1px;が指定されているようです。

github.com

.btn-group {
  .btn + .btn,
  .btn + .btn-group,
  .btn-group + .btn,
  .btn-group + .btn-group {
    margin-left: -1px;
  }
}

しかし、tooltipを使用するとtooltipの対象となっている.btnの後にDOMが追加されてしまい、.btn同士が隣接している状態ではなくなってしまいます。 そうすると、上記cssが適応されないのでレイアウトがズレてしまっているようです。

f:id:umatomakun:20150321203149p:plain

ズレが生じないようにする

対処法としてはdata-containerbody等に設定してあげればOKです。

<div class="btn-group" role="group">
    <button
        type="button"
        class="btn btn-default"
        data-toggle="tooltip"
        data-container="body"
        title="Tooltip">
        Left
    </button>
    <button type="button" class="btn btn-default">Middle</button>
    <button type="button" class="btn btn-default">Right</button>
</div>

参考

Bootstrapの公式サイトにもdata-containerを指定するよう載っていますね。

getbootstrap.com

When using tooltips on elements within a .btn-group or an .input-group, you'll have to specify the option container: 'body' (documented below) to avoid unwanted side effects (such as the element growing wider and/or losing its rounded corners when the tooltip is triggered).