I do have several nested polymer elements created by myself. Currently with using polymers shared styles I'm able to inject custom styling into other elements. Unfortunately this approach is restricted to static use. So at implementation time I do need to know which Element should use which shared style by import the shared style module with <link rel="import" href="my-shared-style.html"> and <style include="my-shared-style"></style>.
But in my use case I do need to inject shared styles into polymer elements at runtime. Is there any possibility to achieve this?
UPDATE
I tried following approach inspired by Günters answer below:
Polymer({
is : 'html-grid-row',
/**
* Inject style into element
* #param {string} style
*/
injectStyle : function(style) {
var customStyle = document.createElement('style', 'custom-style');
customStyle.textContent = style;
Polymer.dom(this.root).appendChild(customStyle);
}
/**
* Additional Elements JS functionality is put here...
*
*/
)}
When I now try to dynamically add style by calling injectStyle('div {font-weight: bold;}') on elements instance at runtime the style module is injected into the element but is not displayed because polymer seems to edit custom-styles text content like the following:
<style is="custom-style" class="style-scope html-grid-row">
div:not([style-scope]):not(.style-scope) {font-weight: bold;}
</style>
Is there a way to prevent polymer from adding the :not([style-scope]):not(.style-scope) prefix to style rules?
UPDATE 2:
Referencing a global shared style using include='my-shared-style' does have the same effect.
Include this shared style which is statically imported globally using html import:
<dom-module id="my-shared-style">
<template>
<style>
div {
font-weight: bold;
}
</style>
</template>
</dom-module>
After dynamically import and referencing shared-style Polymer includes following:
<style is="custom-style" include="my-shared-style" class="style-scope
html-grid-row">
div:not([style-scope]):not(.style-scope) {
font-weight: bold;
}
</style>
SOLUTION
Finally I used a workaround for dynamically inject styling into Polymer elements at runtime by extending the <style> HTML Element with document.register('scoped-style', {extends : 'style', prototype : ...}). The injectStyle(style) method (see above) now creates a <style is="scoped-style"> element directly as child of the Elements root node. Indeed it's inspired by https://github.com/thomaspark/scoper. This works so far for me.
I used something like this successfully to inject styles dynamically
var myDomModule = document.createElement('style', 'custom-style');
myDomModule.setAttribute('include', 'mySharedStyleModuleName');
Polymer.dom(sliderElem.root).appendChild(myDomModule);
The style-module 'mySharedStyleModuleName' needs to be imported somewhere (like index.html).
See also https://github.com/Polymer/polymer/issues/2681 about issues I run into with this approach and https://stackoverflow.com/a/34650194/217408 for more details
Related
I have started development on a vue web component library. Members of my team asked for the potential to remove default styles via an HTML attribute on the web component. I know that I could use CSS class bindings on the template elements, however, I was wondering if there is a way to conditionally include the style tag itself so that I would not need to change the class names in order to include the base styles or not.
Example of a component's structure
<template>
<section class="default-class" />
</template>
<script>
export default {
props: {
useDefault: Boolean
}
}
</script>
<style>
// Default styles included here
// Ideally the style tag or it's content could be included based off useDefault prop
</style>
Potential implementation
<web-component use-default="false"></web-component>
As I read your question; you want to keep <style> both affecting Global DOM and shadowDOM
One way is to clone those <style> elements into shadowDOM
But maybe ::parts works better for you; see: https://meowni.ca/posts/part-theme-explainer/
customElements.define("web-component", class extends HTMLElement {
constructor() {
super()
.attachShadow({mode:"open"})
.innerHTML = "<div>Inside Web Component</div>";
}
connectedCallback() {
// get all styles from global DOM and clone them inside the Web Component
let includeStyles = this.getAttribute("clone-styles");
let globalStyles = document.querySelectorAll(`[${includeStyles}]`);
let clonedStyles = [...globalStyles].map(style => style.cloneNode(true));
this.shadowRoot.prepend(...clonedStyles);
}
});
<style mystyles>
div {
background: gold
}
</style>
<style mystyles>
div {
color: blue
}
</style>
<div>I am Global</div>
<web-component clone-styles="mystyles"></web-component>
I need to make fonts for some of my components bigger when my app is in full screen mode. In my App.jsx I have variable that triggers me adding "fullscreen" class to the root DIV of the whole app. I can go brute force and override it like * { font-szie: 18px; } but thats too simple. I want to override certain classes only (like .some-class * { font-size: 18px; }). Of course React hash stands in my way so here is question: how do I apply my font size to all components in the app?
If you have hashed classes (i.e some-class-[hash]), you can use CSS selector to deal with it.
Like this:
[class^="some-class-"]
The above CSS selector will select all classes which start with "some-class-".
You can read more about CSS selectors here: https://www.w3schools.com/cssref/css_selectors.asp
You can use General Classes like Bootstrap or Tailwind, then you should use it in your public folder and use linkcss`
<head>
<link rel="stylesheet" href="..." />
</ head>
.text-sm {
font-size: 1rem !important;
}
import hashed_classes from "./file.css";
const Component = () => {
return (
<div className={`${hashed_classes.class} text-sm`} />
)
}
My question is pretty basic.
How to add styling from a css-file to a basic vaadin component?
What I do NOT want to use:
PolymerTemplate
getStlye().set(...)
Do I have to #ImportHtml, which includes the css-code or do I have to #StyleSheet with the css-file? And afterwards, do I have to add the "css-style" via .getElement().getClassList().add(...)?
I really need help to have a working simple code example for a Label, Button or whatsever, please. I cannot find anything to satisfy my requirements.
In our documentation we guide to use #ImportHtml in MainView for global styles as a html style module.
In the global style module you can apply themable mixins to change stylable shadow parts, etc. of the components.
In case your target is not in shadow DOM, you can set the styles in custom styles block directly, e.g.
Say you have a Label and TextField in your application
// If styles.html is in src/main/java/webapp/frontend/ path is not needed
#HtmlImport("styles.html")
public class MainLayout extends VerticalLayout implements RouterLayout {
...
Label label = new Label("Title");
label.addClassName("title-label");
add(label);
...
TextField limit = new TextField("Limit");
limit.addClassName("limit-field");
add(limit);
...
}
And in src/main/java/webapp/frontend/styles.html
<custom-style>
<style>
.title-label {
color: brown;
font-weight: bold;
}
...
</style>
</custom-style>
<dom-module theme-for="vaadin-text-field" id="limit-field">
<template>
<style>
:host(.limit-field) [part="value"]{
color:red
}
</style>
</template>
</dom-module>
And your "Title" text will have brown bold font, and the value in text field will be red, but its title un-affected.
See also: Dynamically changing font, font-size, font-color, and so on in Vaadin Flow web apps
I have an HTML document that uses multiple style tags. One of those styles has the following content
<style id='pstyle'>
.p0010, .p0016, .p0022, .p0028, .p0032,
.p0034, .p0038, .p0042, .p0044, .p0046,
.p0048, .p0050, .p0052, .p0054, .p0056,
{
max-width:100%;
background-size:100%;
background-image: url('sprites.png');
}
</style>
document.styleSheets allows me to access the full set of stylesheets used by the document. From there - once I have grabbed the right stylesheet - I can use the cssRules array attribute to access the selectorText attribute of each contained style. However, I have been unable to figure out how to find the "right" style sheet. Whilst I can give the stylesheet an id this does not turn up as an attribute of the document.styleSheets[n] object.
I do a great deal of DOM manipulation but it is mostly with the visual elements in the document. I'd be much obliged to anyone who can tell me how I go about identifying the "right" stylesheet
A plain English version of the task
a. Find the style element - bearing in mind that there will be others - with the id pstyle
b. Read the class names defined therein and do whatever
I'm not sure to understand if you want to get the stylesheet associated with the <style> element, or if you want to retrieve the element from the stylesheet.
So here you'll get both :
// from the element
console.log(pstyle.sheet === document.styleSheets[2]);
// from the stylesheet
console.log(document.styleSheets[2].ownerNode === pstyle);
<style id='pstyle'>
</style>
note that in the snippet it's [2] because stacksnippet does inject stylesheets
And now to get the cssRules and selectorText, you just have to read it from the selected styleSheet:
var pstyle = document.getElementById('pstyle');
// from the element
console.log(pstyle.sheet.cssRules[0].selectorText);
// from the stylesheets
for(var sheet of document.styleSheets){
if(sheet.ownerNode === pstyle){
console.log(sheet.cssRules[0].selectorText);
}
}
<style id='pstyle'>
.p0010, .p0016, .p0022, .p0028, .p0032,
.p0034, .p0038, .p0042, .p0044, .p0046,
.p0048, .p0050, .p0052, .p0054, .p0056
{
max-width:100%;
background-size:100%;
background-image: url('sprites.png');
}
</style>
Let's save I have a .Vue component that I grab off of Github somewhere. Let's call it CompB and we'll add a single CSS rule-set there for a blue header:
CompB.Vue (a dependency I don't own, perhaps pulled from Github)
<template>
...
</template>
<script>
...
</script>
<style lang="scss" scoped>
.compb-header {
color: blue;
}
</style>
I plan to nest CompB into my own project's CompA. Now what are my options for overriding the scoped rule?
After playing around a bit, I think I've got a good approach.
Global overrides
For situations where I want to override the rules in all cases for CompB I can add a rule-set with more specificity like this: #app .compb-header { .. }. Since we always only have one root (#app) it's safe to use an ID in the rule-set. This easily overrides the scoped rules in CompB.
Parent overrides
For situations where I want to override both the global and scoped rules. Thankfully VueJS allows adding both a scoped and unscoped style block into a .Vue file. So I can add an even more specific CSS rule-set. Also notice I can pass a class into CompB's props since Vue provides built-in class and style props for all components:
// in CompA (the parent)
<template>
...
<!-- Vue provides built-in class and style props for all comps -->
<compb class="compb"></compb>
</template>
<script>
...
</script>
<style lang="scss">
#app .compb .compb-header {
color: red;
}
</style>
<style lang="scss" scoped>
...
</style>
(note: You can get more specific and make the class you pass into CompB have a more unique name such as .compa-compb or some hash suffix so there is no potential for collision with other components that use CompB and a class .compb. But I think that might be overkill for most applications.)
And of course CompB may provide its own additional props for adjusting CSS or passing classes/styles into areas of the component. But this may not always be the case when you use a component you don't own (unless you fork it). Plus, even with this provided, there is always those situations where you are like "I just want to adjust that padding just a bit!". The above two solutions seem to work great for this.
You will need to add more specificity weight to your css. You have to wrap that component in another class so you can override it. Here is the complete code
<template>
<div class="wrapper">
<comp-b>...</comp-b>
</div>
</template>
<script>
import CompB from 'xxx/CompB'
export default {
components: {
CompB
}
}
</script>
<style>
.wrapper .compb-header {
color: red;
}
</style>