Dismissible alert component is an container with a close button on top right hand corner.
Let's see it's style, and understand how and why it is implemented in this way.
.alert-dismissible { padding-right: 35px; } .alert-dismissible .close { position: relative; top: -2px; right: -21px; } .close { float: right; }
A container with basic padding and close button
We can use position: absolute;
with top
and right
.
.close { position: absolute; top: 0; right: 0; }
The close button is outside the alert component. Adding
position: relative;
to .alert
can solve
the problem. You can refer to the
Component with header and footer
part for more detail.
.close { position: absolute; top: 0; right: 0; } .alert { position: relative; }
It works, and it is one of the solution, but it is not the best when
we need some padding on close button. We need to hardcode the padding
to top
and right
.
Bootstrap 3 implement another solution. It use float: right;
.close { float: right; }
But the close button affect the position content inside. So Bootstrap 3 add extra padding to the container and use position to
.alert { padding-right: 35px; } .close { float: right; position: relative; right: -22px }
I like this implementation, as the close button is part of the
component. The style merge the button into the component. Although we
have -22px
, but it is not parameter of .alert
.
It is related to size of close button.
One of the limitation is, the button must be the first child element of
.alert
. Otherwise, it will become:
It is because the position depends on the default position.
position: relative;
in component container. It can
prevent the children element go outside the component with
position: absolute;