andrey
andrey

Reputation: 1977

Incapsulate element from page css

I am trying to encapsulate a view from page styles in the following way:

<style type="text/css">
  
    *:not(.component) > button, *:not(.component) > span, *:not(.component) > p{
    		background: green;
    	}
    
    </style>
     
    <div class="component">
    	<button>Button</button>
    
    	<span>Span</span>
    
    	<p>Paragraph</p>
    </div> 

I would like to simplify the css above to have something like:

*:not(.component) > button, span, p{
            background: green;
        }

This applies the condition only for button.

Also I was wondering if this kind of 'encapsulation' will hit the performance?

Any help will be appreciated!

Upvotes: 0

Views: 90

Answers (1)

user2033671
user2033671

Reputation:

If you are open to a little JS you can leverage Shadow DOM which automagically scopes the markup. You may need to use a webcomponent polyfill depending on your target audience till it has better browser support.

var shadow = document.querySelector('.component')
  .attachShadow({
    mode: 'open'
  })
shadow.innerHTML = `
    <button>Button</button>
    <span>Span</span>
    <p>Paragraph</p>
`
p {
    background: green;
  }
<div class="component">
</div>

<div>
  <button>Button</button>
  <span>Span</span>
  <p>Paragraph</p>
</div>

Upvotes: 1

Related Questions