简体   繁体   中英

How to style a custom element directly from CSS?

HTML5 Rocks has a great article on creating custom elements, there is also an article on styling them.

To register a custom element I can do:

var XFoo = document.registerElement('x-foo', {
  prototype: Object.create(HTMLElement.prototype)
});

I now can use x-foo in my body.

<body>
    <x-foo>Hello</x-foo>
</body>

Now my question is: how to style a <x-foo /> element (in the body) from CSS? I would like to keep my HTML clean, so I don't want to append any classes or ids.

The article made me assume it should be:

:host(x-foo) { 
    color: red;
}

You should really use ID's and classes in HTML, it doesn't make your code messy at all. But this should do what you are asking for.

body x-foo{
  color: red;
}

I would recommend to add an id or class to the <x-foo> tag like so <x-foo id="myID"></x-foo>

#myID{
  color:red;
}

After read the article I found this :

CSS

<style> 
  app-panel { 
    display : flex ; 
  } 
  [ is = "x-item" ]  { 
    transition : opacity 400ms ease-in-out ; 
    opacity :  0.3 ; 
    flex :  1 ; 
    text-align : center ; 
    border-radius :  50% ; 
  } 
  [ is = "x-item" ]: hover { 
    opacity :  1.0 ; 
    background :  rgb ( 255 ,  0 ,  255 ); 
    color : white ; 
  } 
  app-panel >  [ is = "x-item" ]  { 
    padding :  5px ; 
    list-style : none ; 
    margin :  0  7px ; 
  } 
</style>

HTML

    <app-panel> 
      <li  is = "x-item"> Do </ li> 
      <li  is = "x-item"> Re </ li> 
      <li  is = "x-item"> Mi </ li> 
    </ app-panel>
  1. In your body(html code) you can add an id or class , whether it's not important costume element or default element .

  2. You can use tag names (here : x-foo) in css.

You can do this easily like other basic css, for example

<style>
  x-foo{
    font-size:45px;
    .........
  }
</style>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM