De-duplicating CSS - css

Our web application (Angular 1, Telerik Kendo, Bootstrap v4) has two themes: "light" and "dark". We produce our CSS using SCSS equivalent to the following:
html {
/* common css properties [snipped] */
&.light {
#import "./kendo/kendo.common-bootstrap.core.min";
#import "./kendo/kendo.bootstrap-v4.min";
#import "./variables.scss";
#import "components.scss";
}
&.dark {
#import "./kendo/kendo.common-material.min";
#import "./kendo/kendo.materialblack.min";
#import "./variables-inverse.scss";
#import "components.scss";
}
}
We set a class on the html element to set the theme. The site will always be "light" or "dark", nothing else. This works perfectly well for us. However, it also results in a lot of duplicated CSS rules, resulting in a larger-than-necessary CSS file. A contrived example of what I mean:
html.light a { margin: 2em; }
html.dark a { margin: 2em; }
If the site is always "light" or "dark", these rules are effectively duplicates that can be simplified to:
a { margin: 2em; }
We use Gulp in our build process.
Question: How can I de-duplicate my CSS rules OR avoid duplicating them in the first place?

Related

Generating CSS from Angular SCSS?

Is there a way to see the CSS that corresponds to the SCSS when we are using SCSS as the preprocessor for Angular?
There is an answer here:
When using angular with scss, how can I see the translated css?
And it mentions using the --extract-css option, however when I try that it looks like it has been deprecated:
sandbox/project $ ng build --extract-css
Unknown option: '--extract-css'
Thoughts?
Styles in Angular Build Files
In your build files the styles of components will actually be compiled in the main.js file. You can find it in the network tab of your browsers developertools.
You will also see a file called styles.css, but this will only contain your global styles. This is because of Angulars view-encapsulation of styles per component. The behavior of angular may change if you change the view-encapsulation strategy as explained here to:
Emulated (default)
ShadowDOM
None
I would not recommend doing that though.
However, if you want you can compile your sass files into css using the command line tool you can install as explained on the official sass website.
You can also just use online sass converters like thisone.
If you are just interested in the global styles here's a reference to How you can switch the format from scss to css in your browser.
Example
app.component.scss
p {
background-color: orange;
}
styles.scss
#import 'default';
p {
color: red;
&:hover {
color: blue;
}
}
default.scss
h1 {
color: teal;
}
Result in Build
styles.css:
h1 {
color: teal;
}
p {
color: red;
}
p:hover {
color: blue;
}
main.js:
AppComponent.ɵfac = function AppComponent_Factory(t) { return new (t || AppComponent)(); };
AppComponent.ɵcmp = /*#__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineComponent"]({ type: AppComponent, selectors: [["app-root"]], decls: 1, vars: 0, template: function AppComponent_Template(rf, ctx) { if (rf & 1) {
_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](0, "lib-my-lib");
} }, directives: [my_lib__WEBPACK_IMPORTED_MODULE_1__.MyLibComponent], styles: ["p[_ngcontent-%COMP%] {\n background-color: orange;\n}\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImFwcC5jb21wb25lbnQuc2NzcyIsIi4uXFwuLlxcLi5cXC4uXFxBbmd1bGFyJTIwUHJvamVjdHNcXGxpYi1leGFtcGxlXFxzcmNcXGFwcFxcYXBwLmNvbXBvbmVudC5zY3NzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0VBQ0Usd0JBQUE7QUNDRiIsImZpbGUiOiJhcHAuY29tcG9uZW50LnNjc3MiLCJzb3VyY2VzQ29udGVudCI6WyJwIHtcclxuICBiYWNrZ3JvdW5kLWNvbG9yOiBvcmFuZ2U7XHJcbn1cclxuIiwicCB7XG4gIGJhY2tncm91bmQtY29sb3I6IG9yYW5nZTtcbn0iXX0= */"] });
*Note the orange background-color in the last line.
This is just a complement to the accepted answer. I wrote it up in a medium article, as it was not immediately obvious as styles.scss is opened first when selecting elements in Chrome Developer Tooling, but styles.css is in the tab right next to it.
https://fireflysemantics.medium.com/viewing-generated-global-css-for-angular-sass-projects-857a6887ff0b

Vue 3 (CLI) imports global styles many times than need

So, I have scss file with global styles. This file seems like that:
#import "colors";
#import "border-radius";
#import "box-shadow";
#import "paddings";
#import "margins";
#import "fonts-famalies";
#import "font-sizes";
#import "transition-durations";
#import "global-path";
#import "mixins";
#import "mixins-properties";
#import "../design/animations/fade-animation";
::v-global(*), ::v-global(*::before), ::v-global(*::after) {
box-sizing: border-box;
outline-color: var(--color-outline__global);
transition: background-color 0.2s linear;
}
::v-global(html), ::v-global(body), ::v-global(#application) {
font-family: var(--font-famaly__comfortaa);
background-color: var(--color-background__global);
color: var(--color-font__content);
margin: 0;
font-size: 95%;
height: 100vh;
overflow-wrap: anywhere;
}
v:global(a) {
color: var(--color-font__link);
}
Styles imports using vue.config.js with this configuration:
module.exports = defineConfig({
transpileDependencies: true,
css: {
loaderOptions: {
sass: {
additionalData: `
#import "#/styles/global/global.scss";
`
}
}
}
})
All good, but when I open developer console in chrome I see picture like that.
When I checked header tag in HTML I see a lot of same css imports. If I comment all css styles - header have a lot of styles still. What am I doing wrong? I think that problem in loader
If you're going to be adding a global import (for example for shared SCSS variables and mixins), don't put ANY global styles in that import.
scss-loader's additionalData modifies each scss file it loads with the given string template. As a result, you're putting an import with your global style definitions at the start of every component's style block.
To fix this, move all your v-global(html) styles and the animations to a different file, which you import once in your index.html or App.vue. Ensure that the file you want to automatically import in your components only contains code that does not generate any styles by themselves (so scss variables, mixins, functions, etc. are fine). It's common that you name this file 'variables.scss' or similar, so no style definitions accidentally end up in this file or its dependencies.

LESS variable overrides and import order

In our app.less file, we import a few variable files, and then the individual component style sheets.
app.less
#import variables.less /* Original app styles/colors */
#import corp-colors.less /* corporate color variables */
#import light-theme.less /* Theme definitions */
#import '../components/style' /* This file contains imports of every component in the app */
The variables.less file defines #link-color...
variables.less
#link-color: #1997CA;
And the light-theme.less redefines it by pulling in the corp color.
light-theme.less
body.light-theme {
#link-color: #corp-blue;
}
corp-colors.less
```less
#corp-blue: #2a60c8;
```
Finally, in my component, I digest the variable for a tab bottom border.
x-component/style.less
li {
&.is-selected {
.tab-label {
border-bottom: 3px solid #link-color;
}
}
}
As the light-theme is imported after variables, I'd expect to see the border color as #2a60c8, but am seeing the original #1997CA instead.
However, if I change the component style to use #corp-blue instead of #link-color, it shows correctly.
Am I overlooking something with import and override ordering?
LESS variables work not like CSS variables, they calculate their values on the compilation stage, not in runtime. It seems like you need to change:
body.light-theme {
#link-color: #corp-blue;
}
to:
#link-color: #corp-blue;

Workaround for CSS variables in IE?

I'm currently developing a web application in Outsystems in which I have the need to customize the CSS, in which I'm using variables. I need to guarantee the app works cross-browser, including in Internet Explorer. IE doesn't support CSS variables, as you can see in the picture below from this source.
Since I have to use CSS variables, is there any workaround for the usage of variables in IE?
Yes there is a way, the same way you make any css compatible: use a specific css fallback that is supported by the browser.
body {
--text-color: red;
}
body {
color: red; /* default supported fallback style */
color: var(--text-color); /* will not be used by any browser that doesn't support it, and will default to the previous fallback */
}
This solution is incredibly redundant and 'almost' defeats the purpose of css variables....BUT it is necessary for browser compatibility. Doing this would essentially make the css variables useless but I implore you to still use them because it will serve as an important reminder to the fact that these values are referenced elsewhere and need to be updated in all cases, otherwise you forget to update every related occurrence of 'color' and then you have inconsistent styling because relevant css values are out of sync. The variable will serve more as a comment but a very important one.
There is a polyfill, which enables almost complete support for CSS variables in IE11:
https://github.com/nuxodin/ie11CustomProperties
(i am the author)
The script makes use of the fact that IE has minimal custom properties support where properties can be defined and read out with the cascade in mind.
.myEl {-ie-test:'aaa'} // only one dash allowed! "-"
then read it in javascript:
getComputedStyle( querySelector('.myEl') )['-ie-test']
From the README:
Features
handles dynamic added html-content
handles dynamic added , -elements
chaining --bar:var(--foo)
fallback var(--color, blue)
:focus, :target, :hover
js-integration:
style.setProperty('--x','y')
style.getPropertyValue('--x')
getComputedStyle(el).getPropertyValue('--inherited')
Inline styles: <div ie-style="--color:blue"...
cascade works
inheritance works
under 3k (min+gzip) and dependency-free
Demo:
https://rawcdn.githack.com/nuxodin/ie11CustomProperties/b851ec2b6b8e336a78857b570d9c12a8526c9a91/test.html
In case someone comes across this, has a similar issue where I had it set like this.
a {
background: var(--new-color);
border-radius: 50%;
}
I added the background colour before the variable so if that didn't load it fell back on the hex.
a {
background: #3279B8;
background: var(--new-color);
border-radius: 50%;
}
Yes, so long as you're processing root-level custom properties (IE9+).
GitHub: https://github.com/jhildenbiddle/css-vars-ponyfill
NPM: https://www.npmjs.com/package/css-vars-ponyfill
Demo: https://codepen.io/jhildenbiddle/pen/ZxYJrR
From the README:
Features
Client-side transformation of CSS custom properties to static values
Live updates of runtime values in both modern and legacy browsers
Transforms <link>, <style>, and #import CSS
Transforms relative url() paths to absolute URLs
Supports chained and nested var() functions
Supports var() function fallback values
Supports web components / shadow DOM CSS
Watch mode auto-updates on <link> and <style> changes
UMD and ES6 module available
TypeScript definitions included
Lightweight (6k min+gzip) and dependency-free
Limitations
Custom property support is limited to :root and :host declarations
The use of var() is limited to property values (per W3C specification)
Here are a few examples of what the library can handle:
Root-level custom properties
:root {
--a: red;
}
p {
color: var(--a);
}
Chained custom properties
:root {
--a: var(--b);
--b: var(--c);
--c: red;
}
p {
color: var(--a);
}
Nested custom properties
:root {
--a: 1em;
--b: 2;
}
p {
font-size: calc(var(--a) * var(--b));
}
Fallback values
p {
font-size: var(--a, 1rem);
color: var(--b, var(--c, var(--d, red)));
}
Transforms <link>, <style>, and #import CSS
<link rel="stylesheet" href="/absolute/path/to/style.css">
<link rel="stylesheet" href="../relative/path/to/style.css">
<style>
#import "/absolute/path/to/style.css";
#import "../relative/path/to/style.css";
</style>
Transforms web components / shadow DOM
<custom-element>
#shadow-root
<style>
.my-custom-element {
color: var(--test-color);
}
</style>
<div class="my-custom-element">Hello.</div>
</custom-element>
For the sake of completeness: w3c specs
Hope this helps.
(Shameless self-promotion: Check)
Make a seperate .css file for your variables. Copy/paste the contents of the variable.css file to the end of your main.css file. Find and replace all the variable names in the main.css file to the hex code for those variables. For example: ctrl-h to find var(--myWhiteVariable) and replace with #111111.
Side note: if you keep the :root{ } in the main.css file and just comment it out, you can use that to track those hex codes later if you want to update your fallback colors.
Another way to do it is declaring colors in a JS file (in my case I'm using react) and then just use the variable you defined in the JS file.
For example:
in globals.js
export const COLORS = {
yellow: '#F4B400',
yellowLight: '#F4C849',
purple: '#7237CC',
purple1: '#A374EB',
}
in your file
import { COLORS } from 'globals'
and then just use COLORS.yellow, COLORS.purple, etc.
body {
--text-color : red; /* --text-color 정의 */
}
body {
color: var(--text-color, red); /* --text-color 정의되지 않으면 red로 대체됨 */
}
body {
color: var(--text-color, var(--text-color-other, blue));
/* --text-color, --text-color-other 가 정의되지 않으면 blue로 대체됨 */
}
There is no way yet in "normal" css but take a look at sass/scss or less.
here is a scss example
$font-stack: Helvetica, sans-serif;
$primary-color: #333;
body {
font: 100% $font-stack;
color: $primary-color;
}
I recommend setting your css variables as sass variables, then using sass interpolation to render the color in your elements.
:root {
--text-color: #123456;
}
$text-color: var(--text-color);
body {
color: #{$text-color};
}
If im not wrong there is a workaround, the CSS #ID Selector. Which should work for IE > 6 I guess.. So you can
.one { };
<div class="one">
should work as
#one {};
<div id="one">

CSS zurb foundation and dhtmlx

I have a project that requires zurb foundation css and dhtml scheduler and the css is not playing very nicely.
There are two issues in particular.
The monthly calendar is misaligned because of the .56em .62em padding on the table.
A bit more complicated is the appointments on the calender.
this is what it looks like. notice the hole in the side menu.
The styles by default that are the problem.
And I need to remove them to properly render the page.
We are using scss version of foundation but I'm not very familiar with its capabilities and the dhtmlx controls do not use it.
So my basic question is how should i change these styles with the least amount of impact to foundation or dhtml?
I'm sure I could use java script but I think that would be a pain as the calender changes having to find all the elements to apply styles again, and i'm really hopping there is a nifty css trick. =)
Thanks!
******* EDIT ***********
The table issue was quickly fixed for chrome and IE by adding another style sheet after foundation to override the conflicting styles. Short and simple.
<style type="text/css" media="screen">
#scheduler_here table tr td, #scheduler_here table tr th
{
padding: 0;
}
#scheduler_here *, #scheduler_here *:before, #scheduler_here *,after {
box-sizing: content-box;
-webkit-box-sizing: content-box;
}
</style>
If you use Foundation 4 (F4) you can pick and choose which parts of foundation CSS are generated by Compass / Sass. Don't forget to run compass compile after you make the change.
edit -> sass/app.scss
// Global Foundation Settings
#import "settings";
// Comment out this import if you are customizing you imports below
// #import "foundation";
// Import specific parts of Foundation by commenting the import "foundation"
// and uncommenting what you want below. You must uncomment the following if customizing
#import "foundation/components/global"; // *always required
#import "foundation/components/grid";
#import "foundation/components/visibility";
#import "foundation/components/block-grid";
#import "foundation/components/type";
#import "foundation/components/buttons";
#import "foundation/components/forms"; // *requires components/buttons
#import "foundation/components/custom-forms"; // *requires components/buttons, components/forms
#import "foundation/components/button-groups"; // *requires components/buttons
#import "foundation/components/dropdown-buttons"; // *requires components/buttons
#import "foundation/components/split-buttons"; // *requires components/buttons
#import "foundation/components/flex-video";
#import "foundation/components/section";
#import "foundation/components/top-bar"; // *requires components/grid
#import "foundation/components/orbit";
#import "foundation/components/reveal";
#import "foundation/components/joyride";
#import "foundation/components/clearing";
#import "foundation/components/alert-boxes";
#import "foundation/components/breadcrumbs";
#import "foundation/components/keystrokes";
#import "foundation/components/labels";
#import "foundation/components/inline-lists";
#import "foundation/components/pagination";
#import "foundation/components/panels";
#import "foundation/components/pricing-tables";
#import "foundation/components/progress-bars";
#import "foundation/components/side-nav";
#import "foundation/components/sub-nav";
#import "foundation/components/switch";
#import "foundation/components/magellan";
// #import "foundation/components/tables"; // prevent Table CSS from loading
#import "foundation/components/thumbs";
#import "foundation/components/tooltips";
#import "foundation/components/dropdown";
Another option, if you know how you would like to change the padding, borders, etc. to match your other included elements is you could edit the _settings.scss, lines 1064 - 1097 where it has variables for tables. I am showing the variables here unmodified to illustrate what can be changed.
//
// Table Variables
//
//// Background color for the table and even rows
// $table-bg: #fff;
// $table-even-row-bg: #f9f9f9;
//// Table cell border style
// $table-border-style: solid;
// $table-border-size: 1px;
// $table-border-color: #ddd;
//// Table head styles
// $table-head-bg: #f5f5f5;
// $table-head-font-size: emCalc(14px);
// $table-head-font-color: #222;
// $table-head-font-weight: bold;
// $table-head-padding: emCalc(8px) emCalc(10px) emCalc(10px);
//// Row padding and font styles
// $table-row-padding: emCalc(9px) emCalc(10px);
// $table-row-font-size: emCalc(14px);
// $table-row-font-color: #222;
// $table-line-height: emCalc(18px);
//// Display and margin of tables
// $table-display: table-cell;
// $table-margin-bottom: emCalc(20px);
If you have time and want to go even further, you can pull the foundation/components/tables.scss file into your local project, modify it however you like and link to the modified version as above. You can find the original files by running gem which zurb-foundation I have installed with rvm so I get something like ~/.rvm/gems/ruby-1.9.3-p286/gems/zurb-foundation-4.1.5/lib/zurb-foundation.rb from the zurb-foundation-4.1.5 directory the file is located in scss/foundation/components and called _tables.scss

Resources