I have a page with a Bootstrap 4 toast where I set the toast's postion as postion: fixed
. The whole toast part looks like this:
<div class="container mt-5">
<button type="button" class="btn btn-primary" id="liveToastBtn">Toast it</button>
<div id="toastContainer" style="position: fixed; top: 1.5vw; right: 1vw; bottom: 4.5vw; z-index: 9;">
<div class="toast show" role="alert" aria-live="assertive" aria-atomic="true">
<div class="toast-header">
<img src="..." class="rounded mr-2" alt="...">
<strong class="mr-auto">Bootstrap</strong>
<small>11 mins ago</small>
<button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="toast-body">
Hello, world! This is a toast message.
</div>
</div>
</div>
</div>
The full working code you find in this JSFiddle.
The works works great as is, but now I want to set the width of the toast to something around 50% of the view port. In the <div id="toastContainer"...>
line I tried setting the width
property:
<div id="toastContainer" style="position: fixed; top: 1.5vw; width: 50%; right: 1vw; bottom: 4.5vw; z-index: 9;">
and alternatively I tried setting left
:
<div id="toastContainer" style="position: fixed; top: 1.5vw; left: 50%; right: 1vw; bottom: 4.5vw; z-index: 9;">
but in both cases the width of the appearing toast does not change (only its horizontal position).
How can I set the width of this Bootstrap 4 toast?
The problem comes from the max-width
applied to the .toast
, you can unset
it.
Then you can set your width: 50vw;
to the #toastContainer
(or .toast
).
const toastEl = document.querySelector('.toast');
let toast = new bootstrap.Toast(toastEl, {
autohide: false
})
const toastButton = document.getElementById("liveToastBtn")
toastButton.addEventListener("click", function() {
console.log("Button was clicked!");
toast.show()
});
#toastContainer {
width: 50vw;
}
#toastContainer .toast {
max-width: unset;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
<div class="container mt-5">
<button type="button" class="btn btn-primary" id="liveToastBtn">Toast it</button>
<div id="toastContainer" style="position: fixed; top: 1.5vw; right: 1vw; bottom: 4.5vw; z-index: 9;">
<div class="toast hide" role="alert" aria-live="assertive" aria-atomic="true">
<div class="toast-header">
<strong class="mr-auto">Bootstrap</strong>
<small>11 mins ago</small>
<button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="toast-body">
Hello, world! This is a toast message.
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>