Font Awesome is not working in my shadow DOM since I have the following in it to prevent styles from leaking in and out:
:host {
all: initial; /* 1st rule so subsequent properties are reset. */
display: block;
contain: content; /* Boom. CSS containment FTW. */
}
I'm able to use other stylesheets by just inlining them within the :host property, but that doesn't work with Font Awesome since it uses relative paths in its stylesheet.
I found this post and tried it with the scoped CSS I implement, but the icons show as squares, as can be seen in my example.
I had the same issue with StencilJS.
After hours of struggle and the answer from #Intervalia I was able to fix it.
The problem is that the browser doesn't load the font files when they are only included in the shadow dom (your custom web component). This means that the fonts also has to be included in the normal html file (aka light DOM) so that the browser can detect and load them in order to make them available in the shadow dom.
In my case I didn't use Font awesome instead it was a custom font but I tried it a second time with font awesome and a clean Stenciljs project. The solution is always the same doesn't matter which custom font you need.
Step 1: Move the font into your project. I created a seperate "assets" folder inside the "src" folder to have access from all the components. In this example I downloaded font awesome for web environment https://fontawesome.com/download. (I wouldn't recommend "npm install" since you have to use it in the index.html too)
Step 2: Prepare your web component (in this case my-component.tsx). You can import multiple css files using the styleUrls property. Just import the fontawesome css from your assets directory.
import { Component, Prop, h } from '#stencil/core';
#Component({
tag: 'my-component',
styleUrls: [
'my-component.css',
'../../assets/fontawesome/css/all.css'
],
shadow: true
})
export class MyComponent {
#Prop() first: string;
render() {
return <div> <i class="fas fa-question-circle"></i> </div>;
}
}
Step 3 prepare the file where you want to use the component (in this case index.html). The important line is the "link" tag. This includes the "font awesome css" again and force the Browser to really download the fonts.
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<title>Stencil Component Starter</title>
<link rel="stylesheet" type="text/css" href="./assets/fontawesome/css/all.css">
</head>
<body>
<my-component first="Stencil" last="'Don't call me a framework' JS"></my-component>
</body>
</html>
I know it feels wrong and looks weird but it is not enough to include font awesome only in the index html or in the web component. It must really be included in both files. That doesn't mean the Browser will load it multiple times - it will only be loaded once.
That means that you can't deliver the font with the web component - as far as i know. This isn't a stenciljs bug this is a general problem of the browsers. Please let me know if you have better solutions.
Just for fun here is a screenshot that shows that the browser doesn't load the fonts when it is only included in one file. http://prntscr.com/p2f9tc
Update 05.10.2019:
If you want to use your font inside your web-component the explanation above is correct and still necessary. But you can also use the slot tag inside the web-component. Than you automatically bypass the font from outside (the html) into the web-component. But notice it only works for the stuff you write between the tags of your web component.
That means you can use <my-component> <i class="your-font"/> </my-component>. In this case you don't have to import the font into the web components.
One thing I have noticed is that if the page does not load the CSS file then the shadowDOM won't load it either.
I really think that the only problem us that if the font is not defined on the page that it will not work in the component since the rest of the CSS seems to properly apply to the shadowDOM elements.
This example shows just the shadowDOM trying to load the CSS and it does not work:
let template = `
<style>
:host {
display: block;
}
</style>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<header>
<h1>DreamLine</h1>
<nav>
<ul>
<li>Tour</li>
<li>Blog</li>
<li>Contact</li>
<li>Error</li>
<li><i class="fa fa-search"></i> Search</li>
</ul>
</nav>
</header>
`;
class MyEl extends HTMLElement {
connectedCallback() {
this.attachShadow({mode: 'open'}).innerHTML = template;
}
}
customElements.define("blog-header", MyEl);
<i class="fa fa-battery-full" style="font-size: 45px;"></i>
<hr/>
<blog-header></blog-header>
<hr/>
And this example shows both the page and the shadowDOM loading it and it works:
let template = `
<style>
:host {
display: block;
}
</style>
<header>
<h1>DreamLine</h1>
<nav>
<ul>
<li>Tour</li>
<li>Blog</li>
<li>Contact</li>
<li>Error</li>
<li><i class="fa fa-search"></i> Search</li>
</ul>
</nav>
</header>
`;
class MyEl extends HTMLElement {
connectedCallback() {
const styles = document.querySelector('link[href*="fontawesome"]');
this.attachShadow({mode: 'open'}).innerHTML = template;
if (styles) {
this.shadowRoot.appendChild(styles.cloneNode());
}
}
}
customElements.define("blog-header", MyEl);
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<i class="fa fa-battery-full" style="font-size: 45px;"></i>
<hr/>
<blog-header></blog-header>
<hr/>
The code I like to use looks for the <link> tag I want in the body and then uses a clone of that tag inside the shadowDOM. This way my component is not out of sync. Yes, this can cause problems if the component was not expecting a change in the CSS but I find it works well for my projects.
If you don't need shadow: true then you can load the all.min.css directly via the index.html or the main application. Even loading the all.min.js file works.
If you need it within the shadow dom, then you need to load the all.min.css in index.html and also load it within shadow root using something like this.
`
componentDidLoad(): void {
this.hostElement.shadowRoot
.getElementById("some_Id")
.insertAdjacentHTML(
"afterbegin",
`<link rel="stylesheet" href="${getAssetPath(
"/fontAssets/fontawesome-free/css/all.min.css"
)}" />`
);
}
`
I wanted to share what I did for loading in Font Awesome icons to my stencil components (shadow enabled)...
After several hours into researching this topic, I think I've discovered a solution that will be the most efficient for my components to be bundled in a agnostic way and free of any additional style sheet includes in the HTML header.
My solution was to use the stencil-inline-svg module and then import the svg file directly from the Font Awesome module like this:
// the reference to the svg can be anything (searchIcon name).
// just make sure to import the correct svg from fontawesome node modules.
import searchIcon from 'fontawesome/svgs/regular/search.svg';
#Component({
tag: 'search-icon',
styleUrl: 'search-icon.scss',
shadow: true,
})
export class SearchIconComponent {
render(){
return (
{/* Not ideal to use innerHTML but this renders the full SVG markup */}
<span class="search-btn" innerHTML={searchIcon}></span>
)
}
}
Now, I can set css rules to modify the color and size of my icon like this
.search-btn {
width: 40px; // Set SVG size at the parent.
svg path {
fill: #fff; // Update svg path color.
}
}
Obviously this requires a little bit of Font Awesome icon knowledge so you know which icons to import.
Shadow Doms's style is scoped. And it does not interfere with outer style
FWIW I created a helper method to create a link for font-awesome at the parent page level. Not sure if this is in violation of any custom-elements/Web Components standards but I'll go ahead and post here in hopes that I'll be corrected :) It works for my use case w/ internal web applications for now though.
export const addFontAwesomeStyles = () => {
injectStylesheet("https://use.fontawesome.com/releases/v5.13.0/css/all.css");
injectStylesheet("https://use.fontawesome.com/releases/v5.13.0/css/v4-shims.css");
}
export const injectStylesheet = (href: string) => {
const links = document.head.querySelectorAll("link");
// Already been injected
for(let l in links)
if(links[l].href == href) return;
const link = document.createElement('link');
link.rel = "stylesheet";
link.href = href;
document.head.appendChild(link)
}
Then in your StencilJS component's construtor you can use it like so:
//...
constructor() {
addFontAwesomeStyles();
}
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`} />
)
}
I have two .jsx files that represent their respective components.
The first one is, Blog.jsx
import React from "react";
import '../assets/css/blog.css';
export const Blog = () => (
<div>
<h1>Hello Blog</h1>
</div>
)
With its respective CSS file, blog.css
div { background: #ff481f; }
and the second one is, Landing.jsx
import React from "react";
import '../assets/css/landing.css'
export const Landing = () => (
<div>
<h1>Hello Landing</h1>
</div>
)
With its respective CSS file, landing.css
div { background: #86ff2b; }
I have added routing and called instances of those two components on the App.js file which is the default file of a React application. After running the application, when navigated to components, I faced a problem that the background color is the same for both of the components (It loads landing.css only and never changes).
How can I fix that problem that each component only uses its respective .css file and loads it?
By default webpack and other build tools will compile all CSS files into one, even if css was imported in separate JSX files. So you can't use different CSS files and expect you don't affect on another part of page.
You have some options:
Use BEM for naming class names.
Use cssModules. In this case elements will have their own css class name and styles will not affect any other elements except if you use :global selector.
css-module
Using html tags as css selectors is a bad practice (because there is the behaviour you describe).
You should use only css classes or inline styles (using id's is another bad practise, id's have high priority).
div {
width: 20px;
height: 20px;
}
#id {
background: red;
}
.class {
background: green;
}
<div id="id" class="class"></div>
In case using css classes there is the same problem (when you have two similar classes). And this case is decided using css modules (set of rules of building) or you can use css-in-js (external library) which has its pros and cons. Also you can use BEM (methodology) and if your application is not big you can avoid this trouble.
css modules will add to your classes random hash and instead .my-awesome-class-name you will get .my-awesome-class-name-dew3sadf32s.
So, if you have two classes .class in the first file and .class in the second file in the end you will get two classes .class-dew23s2 and .class-dg22sf and you styles will resolve as expected.
css-in-js is a similar way except you should write your styles using javascript with some profits like including only those styles that are needed at the moment (what you are looking for right now) and several others.
You can code using pure css / scss / postcss / etc but many companies already choose between css modules and css-in-js.
BEM is just naming conventions for your class names.
And lastly - if you use inline-styles using react you should remember:
{} is constructor of object and {} returns new object on every call, it's mean if you write something like:
class MyAwesomeComponent extends Component {
render() {
return <div style={{color: "red"}}></div>;
}
}
or
class MyAwesomeComponent extends Component {
render() {
const divStyles = {color: "red"};
return <div style={divStyles}></div>;
}
}
div will re-render every time your render will call because div takes new prop.
Instead, you should define your styles (for example) in outside of your class:
const divStyles = {color: "red"};
class MyAwesomeComponent extends Component {
render() {
return <div style={divStyles}></div>;
}
}
Don't define your css using HTML tags because it will affect your entire application.
use className,id or inline styling.
like- App.css
.myApp{ color: red;}
#myApp2{ color: blue;}
App.js
import './App.css'
<div className="myApp">color changed by className</div>
<div id="myApp2">color changed by id</div>
<div style={{color:'red'}}>color changed by inline object styling</div> // inline styling
This is not the best solution if you are looking forward to improve yours css imports/loads.
However could be the best solution if you dont want to go in deep in css, resolve the problem fast and keep working with HTML tag.
You can add a div for each component, define an Id for the div and wrap the component. Afterwards in the component's css fies you are going to define all the styles starting with the #id so all the css classe or HTML tag will affect just the corresponding component.
//App render in root
ReactDOM.render(
<App />,
document.getElementById('root')
);
//App
function App(props){
return [
<Blog />, <OtherComponent />
]
}
//Blog component
function Blog(props){
return <div id="blog">
<h1>I am Blog</h1>
</div>
}
//Other component
function OtherComponent(props){
return <div id="otherComponent">
<h1>Im am other component</h1>
</div>
}
/* blog.css*/
#blog h1{
color:yellow;
}
/* otherComponent.css*/
#otherComponent h1{
color:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
I’m styling my app. Familiar with the basic theming components, SASS etc... But one thing that stands out and it not making sense is why when I preview the source in a running app how lots of extra CSS classes are added. I’m my case I am simply trying to change the menu header background. In my app.html file I have;
<ion-header>
<ion-toolbar>
<ion-title>Menu</ion-title>
</ion-toolbar>
</ion-header>
Which translates to;
<ion-header class="header header-md">
<ion-toolbar class="toolbar toolbar-md">
<div class="toolbar-background toolbar-background-md" ng-reflect-klass="toolbar-background" ng-reflect-ng-class="toolbar-background-md"></div><div class="toolbar-content toolbar-content-md" ng-reflect-klass="toolbar-content" ng-reflect-ng-class="toolbar-content-md">
<ion-title class="title title-md"><div class="toolbar-title toolbar-title-md" ng-reflect-klass="toolbar-title" ng-reflect-ng-class="toolbar-title-md">Menu</div></ion-title>
</div></ion-toolbar>
</ion-header>
I see that there seems to be a pattern of 'ion-element' translating to 'element element-md'. But it gets a little strange for elements such as 'ion-toolbar' as this adds a div
<div class="toolbar-background toolbar-background-md" ng-reflect-klass="toolbar-background" ng-reflect-ng-class="toolbar-background-md">
I’d like to understand how this translation process works for me I'd like to create some tidy CSS as its looking a bit unwieldy to me!
ion-header is an angular directive (as is ion-toolbar). Directives can have an associated HTML template and javascript. The extra classes are added by the javascript that belongs to each directive. The code below demonstrates an angular directive where a class is added to the original element. If you inspect the results you can also see an extra div being added - that is the result of the directive's template being added to the DOM.
(function() {
var app = angular.module("soDemo", []);
app.directive("soDirective", SoDirective);
function SoDirective() {
var directive = {
restrict: 'E',
scope: {},
link: link,
template: '<div class="content">My directive contents</div>'
};
return directive;
///////////////////
function link(scope, element) {
element.addClass('sample-class');
console.log(element.html());
}
}
})();
.sample-class {
display: block;
border: 1px solid red;
}
.content {
font-style: italic;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="sample" ng-app="soDemo">
<so-directive></so-directive>
</div>
If you look at the Header Ionic API Docs, for <ion-header> you'll see there are Sass variables for 3 platforms - the abbreviation to right of colon is used to target platform specific styling rules:
iOS : ios
Material Design (default if in browser like Chrome) :md
Windows Platform : wp
Plaform specific styles confirm that here
When you do ionic serve --lab you have the option to choose platform and get a feel for the default files render.
When you want to target CSS for specific platforms, then the
nomenclature is: [<elementname>-<platform-abbreviation>]
Here's a more complete list of SASS variables for the different Ionic Components.
In your project there is a themes/variables.scss where you can use those values.
You can define your own SCSS variables like $my-padding:5px; in here and then use that in your custom component CSS, and consequently have that constant declared once and you can globally apply.
So my-component.scss has
[ion-item] {
padding: $my-padding;
}
The toolbar source folder is here.
toolbar-header.ts contains the #Directive selector 'ion-header' for <ion-header> Typescipt class name: Header
toolbar.ts contains the #Directive selector 'ion-toolbar' for <ion-toolbar> Typescript class name: Toolbar
There are scss files for the platforms..
toolbar.ios.scss
toolbar.md.scss
toolbar.wp.scss
They seem to import:
ionic.globals.scss
Furthermore you can configure things in your app-module.ts.
#ngModule({
....
imports: [
IonicModule.forRoot(MyApp, { // settings object
iconMode: 'ios', // all platforms globally use ios icons
tabsHighlight: true, // seems to work only on android
platforms: {
android: { tabsPlacement: 'top' // platform specific
}
}
})
This should give you an insight
I start the project with nuxt.js / express.
We have developed style scoped for each component (.vue) in nuxt.js. So, when routing , the property is overlaid on the same class name (style), so the page does not display properly.
1. What is the correct use of 'style scoped'?
2. Or should the routing process be <a> rather than <nuxt-link>?
What is the correct use of 'style scoped'?
The <style scoped></style> notation is not ambiguous, as the scoped attribute suggests, all the CSS elements defined within this scope apply only to the current component. If the CSS element exists globally, the scoped one -having the same name and type- takes precedence, that is, it overrides the globally defined CSS element.
For example, let us define in /components folder 3 components Component1.vue, Component2.vue, Component3.vue:
Component1.vue:
<template>
<div class="yellow-text">Component 1</div>
</template>
<script>
export default {
name: 'Component1'
}
</script>
<style>
.yellow-text {
color: yellow;
}
</style>
Component2.vue:
<template>
<div class="yellow-text">Component 2</div>
</template>
<script>
export default {
name: 'Component2'
}
</script>
<style scoped>
.yellow-text {
color: red;
}
</style>
Component3.vue:
<template>
<div class="yellow-text">Component 3</div>
</template>
<script>
export default {
name: 'Component3'
}
</script>
In Component1.vue, the text will be displayed in yellow.
In Component2.vue, the text will be displayed in red because the scoped CSS class takes precedence over the globally defined one in Component1.vue.
In Component3.vue, the text will be displayed in yellow.
So to respond to your question: there is no correct way because there is only one way to do that, and the meaning is not subject to any form of interpretation.
Or should the routing process be rather than ?
Even if <nuxt-link /> is rendered as <a href>, the documentation clearly states the former must be used to navigated through the Nuxt.js application and In the future, we will add features to the component, like pre-fetching on the background for improving the responsiveness of Nuxt.js Applications.