Search code examples
htmlcssweb-componentnative-web-component

Why I cannot set sizes on a element that is a WebComponent


I am trying to set width and height in a WebComponent using the :host selector, but the sizes do not change. Here is the template for the component:

<template>
  <style>
    :host {
      width: 100px;
      height: 100px;
      background-color: rebeccapurple;
    }
  </style>

  <h1>Content</h1>
</template>

What I need to do is adding a div as a container and set the size of it

<template>
  <style>
    div {
       width: 100px;
       height: 100px;
       background-color: rebeccapurple;
    }
  </style>

  <div>
    <h1>Content</h1>
  </div>
</template>

I wanted to understand why this is not possible and the reason for it. Or if there are better way to resolve that.

Here is a JSBin of it: http://jsbin.com/gesovagapi/edit?html,css,js,output


Solution

  • By default custom components are created with display: inline;. If you want your component to take a specified width/height, set its display property to block or inline-block. For example:

      <style>
        :host {
          display: inline-block;
          width: 100px;
          height: 100px;
          background-color: rebeccapurple;
        }
      </style>