Skip to content
Tech News
← Back to articles

Phoenix LiveView 1.2

read original get Phoenix LiveView Book → more articles
Why This Matters

LiveView 1.2 introduces the ability to colocate CSS within HEEx templates, enhancing component encapsulation and styling scope. This update streamlines the development process by integrating CSS management into the existing LiveView workflow, leveraging modern CSS @scope rules for better style isolation. These improvements benefit developers by simplifying styling workflows and improving component modularity in Phoenix applications.

Key Takeaways

LiveView 1.2.0 is available now!

To update from LiveView 1.1 to 1.2, simply update the version requirement in your mix.exs file and re-fetch your dependencies:

{ :phoenix_live_view , "~> 1.2.0" }

Colocated CSS

In LiveView 1.1, we introduced Colocated Hooks and Colocated JavaScript, allowing you to write hooks directly inside any HEEx template. LiveView 1.2 builds on the background work done for Phoenix.LiveView.ColocatedJS to allow you to colocate CSS in HEEx too.

def table ( assigns ) do ~H""" < style :type = { MyApp.ColocatedCSS } > thead { color : ... ; } tbody , tr : hover { ... } </ style > < table > ... </ table > """ end

As with Colocated JS, the :type attribute tells LiveView to extract the content of the tag at compile time into a special phoenix-colocated folder in your _build directory. This is then picked up by your bundler (usually Tailwind or Esbuild) and processed as part of your normal CSS pipeline.

That’s the easy part though. What you usually want when defining colocated styles is to scope them, such that they don’t accidentally apply to other elements on the page from different components. Modern CSS has a relatively new @scope rule, which allows us to do just that, with some caveats.

The @scope rule

@ scope (scope root ) to (scope limit ) { /* … */ }

... continue reading