Liveview Alert Message Styling with Tailwind CSS

Here’s my situation

I am trying to style Alert messages in my project. For success messages, I would like the background of the message to be green. But what happens is, the background green stays on the page like it s fixed. I want that background only when the alert message is returned.

Here is my code,


<main role="main">
<p class="alert-info" role="alert"
    phx-value-key="info"><%= live_flash(@flash, :info) %>
  <span class="absolute inset-y-0 right-0 flex items-center mr-4">
    <svg class="w-4 h-4" role="button" viewBox="0 0 20 20"> <path d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" fill-rule="evenodd"></path></svg>

  <%= @inner_content %>


    @apply relative py-3 pl-4 pr-10 leading-normal text-green-700 bg-green-100 rounded-lg;


|> put_flash(:info, "User created successfully")

This is what I get when the alert message is returned

But this background seems fixed

Any help is appreciated.
Thanks! :smiley:

1 Like

your not gating any logic here, example I don’t see anything like <% if live_flash(@flash, :info) do %>

Thus there’s no logic to show or hide said <p class="alert-info" given there are or are not flash messages.

In other words, check for flash messages first before rendering the dom element it will use.

Could you try moving the span outside of the p tag? Right now you are also styling that with class="alert-info" as well as the flash message.

I know it has been a while and maybe no longer relevant. But maybe someone else will stumble upon this post. I guess the issue here is the default styling which is still applied.

Phoenix LiveView comes with a clever CSS rule

.alert:empty {
  display: none;

This works quite well as long as you use their default markup. The moment you add DOM elements to the default <p> tag, it is no longer empty. Therefore, the browser wont hide it and you see an empty green tag.

I am not sure if there is a better way, but @polygonpusher 's solution should work.