Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lit-Element: How do I set global/reset css

What is the current best practice to set global/reset CSS if I'm using Lit-element?

I have tried 1) Inline them in <style> in my document root, 2) Construction stylesheet like this answer

<script>
  var css = new CSSStyleSheet()
  css.replace('@import url("./style/static/reset.css")')
  document.adoptedStyleSheets = [css]
</script>

but nothing works...

EDIT My reset.css:

blockquote,
body,
dd,
dl,
fieldset,
figure,
h1,
h2,
h3,
h4,
h5,
h6,
hr,
legend,
p,
pre,
button,
ul {
  margin: 0;
  padding: 0;
}

img {
  max-width: 100%;
}

I'm building on top of folder structure scaffolded from https://open-wc.org/guide/#quickstart

like image 537
kyw Avatar asked Aug 29 '19 09:08

kyw


Video Answer


1 Answers

This won't work as you expected because LitElement by default uses Shadow DOM which is designed to prevent external CSS from affecting the component's inner tree (and vice versa)

The only way to affect the styles inside a web component is if the component uses CSS variables or if properties that inherit styles are undefined inside the web component (for more info check this guide)

However, if this is a project fully based on LitElement, you can share styles between components quite easily and use that to do this reset:

  1. First create a js file for your shared css (e.g. reset-css.js)

import { css } from 'lit-element';

export default css `
blockquote,
dd,
dl,
fieldset,
figure,
h1,
h2,
h3,
h4,
h5,
h6,
hr,
legend,
p,
pre,
button,
ul {
  margin: 0;
  padding: 0;
}

img {
  max-width: 100%;
}
`;
  1. Then import your style in your components

import {LitElement, html, css} from 'lit-element';

// include your reset styles
import resetCSS from './reset-css.js';

class MyComponent extends LitElement {

  static get styles() {
    // this is the important part, this array includes our resetted styles and this components styles
    return [
      resetCSS, 
      css`
        h1 {
          color: blue;
        }
      `
    ]; 
  }
  
  render() {
    html`<h1>Something Blue</h1>`
  }
}

And just like that, any component which includes the shared reset styles will use them

like image 73
Alan Dávalos Avatar answered Oct 28 '22 03:10

Alan Dávalos