Home > Software design >  When applying the same style to a component and a 'div' element, why do they behave differ
When applying the same style to a component and a 'div' element, why do they behave differ

Time:12-01

Suppose I have a component with a selector selector: 'app-container1' and the following template :

<div style="border:2px solid blue;margin:3px;overflow:clip;display:flex">
  <button>test</button>
  <button>test</button>
  <button>test</button>
</div>

And a component with a selector selector: '[app-container2]' and the following template :

<div style="border:2px solid blue;margin:3px;overflow:clip;display:flex">
  <button>test</button>
  <button>test</button>
  <button>test</button>
</div>

And a simple div element :

<div style="border:2px solid blue;margin:3px;overflow:clip;display:flex">
  <button>test</button>
  <button>test</button>
  <button>test</button>
</div>

I then wrap them inside a container (another div) :

<div style="max-width: 32rem;height:32rem;background-color: red;padding-left: 5rem;">

<!-- container1 -->
  <app-container1 style="border:2px solid black;max-width: 22rem;margin:2rem;"></app-container1>

<!-- container2 -->
  <div app-container2 style="border:2px solid black;max-width: 22rem;margin:2rem;"></div>

<!-- div -->
  <div style="border:2px solid black;max-width: 22rem;margin:2rem;">
    <div style="border:2px solid blue;margin:3px;overflow: clip;display:flex">
      <button>test</button>
      <button>test</button>
      <button>test</button>
    </div>
  </div>

</div>

screenshot of the result

I expect all three to behave exactly the same. However, while it is the case for the div element and app-container2, it is not for app-container1. Why ? And if possible, how can I make app-container1 to behave the same as the others ?

CodePudding user response:

The problem here is that new components created have the css property display:inline by default, whereas the default display value for a <div> is usually block.

Components who have the value inline take up as much space as their child components. That's why is not possible to set some width properties on components itself without changing the display property.

From your screenshot it looks like you basically want your component to always take up the whole row. You should define this component as display:block then.

This can be done from the parent (like you already passed styles to the component) or from the child itself like this:

:host {
  display: block;
}

I prefer the second approach, since in this case the component itself is aware of it's styles.

  • Related