Can I make an element inherit the properties of other elements? - javascript

We're providing a pre-populated WordPress site for multiple members to use on their servers. The theme has a selector where they can customize their heading colours and fonts. Each member will have different colours based on their branding.
The site also includes a knowledgebase plugin and it uses its own colours which can be customized within its interface. Instead, we'd like to be able to set the knowedgebase colours/properties based on the theme's colour palette. (Ultimately, we'd like the member to only have to change the colors for the theme in one place rather than customize every single plugin.)
So, if H1 is globally set to blue, we'd like to be able to tell the knowledgebase's element (.kb-header) to be the same colour as H1.
Is this at all doable via CSS or Javascript or something?
Many thanks!

You can make an element to inherit the properties of a parent element. For example:
p { color: red; }
a { color: inherit; }
<p>Paragraph with link</p>
But definitely this won't work for what you're asking if your .kb-header is not a child of your h1.
Instead you could use different approaches to get the desired result. For example with custom properties (a.k.a CSS variables)
:root {
--user-color: red;
}
h1 {
color: var(--user-color);
}
.kb-header {
color: var(--user-color);
}
<h1>Title</h1>
<header class="kb-header">This is the header</header>
This way you could, for example, output your :root selector defining all your custom properties in your <head> tag using PHP. And your CSS would be totally independent from it.

If you want to inherit (Object Oriented Programing like) if the html tags doesn't have any relationship, you can use SCSS, for example SASS, it's a text pre processor that generates the CSS with a CSS-like coding with the addition that you can use variables and much more.
For more details visit SASS lang webpage i think this can help you a lot for mostly all your projects.
If you don't want to use SASS, you can even use javascript (with or without libraries) to reach this job, as plain CSS is not capable to conditionally apply styles between non-related tags.

I've written a miniature version of what you're looking for. Hope this helps :P
<html>
<style>
h1 {
background-color: blue;
}
</style>
<body>
<h1>Hey!</h1>
<div class="kb-header">I'm a div :)</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var bgColor = $("h1").css("background-color");
$(".kb-header").css({"background-color": bgColor});
});
</script>
<body>
</html>

In CSS you can combine selectors with a comma and have a single block of rules for both:
.a, .b { property: value; }.
And still style one or another selector with other declarations (example below).
When selectors are unrelated, it causes maintenance problems but if it's generated by a theme generator, that should be OK (you don't want to style those given components but have a clear documented list of what has to be styled with a set of colors).
h1,
.kb-header {
color: darkred;
}
h1 {
font-size: 2rem;
}
#media (min-width: 961px) {
.kb-header {
border: 1px solid tomato;
}
<h1>Title</h1>
<p>Unstyled paragraph</p>
<header class="kb-header">This is the header</header>
You can also add a utility class to all elements that are to be styled with a border, a background color and a color:
/* Theme 1
Primary color: #0055D0
Secondary color: #080;
*/
.c-primary {
color: #0055D0;
}
.bd-secondary {
border: 1px solid #080;
}
/* Common styles */
h1 {
font-size: 2rem;
}
.kb-header {
padding: 1rem;
}
<h1 class="c-primary">Title</h1>
<header class="kb-header bd-secondary c-primary">This is the header</header>
Other answers talking about a Sass environment (or other preprocessors like PostCSS and LESS) and CSS "Variables" (if you don't have to support old browsers like IE11 and Edge ~15 + Saf (iOS and OS X) 9.2 https://caniuse.com/#search=custom%20prop are also fine solutions to your problem IMHO.

Related

An easy way to switch styles between multiple elements in Javascript?

Let's say I have following situation which I have to switch the style for several elements and switch them back when a specific condition is met.
let div = document.querySelectorAll('div')
document.querySelector('button').addEventListener('click', function() {
div[0].classList.toggle("div1")
div[1].classList.toggle("div2")
div[2].classList.toggle("div3")
div[0].classList.toggle("new1")
div[1].classList.toggle("new2")
div[2].classList.toggle("new3")
})
.div1 {
color: red;
}
.div2 {
color: green;
}
.div3 {
color: grey;
}
.new1 {
color: yellow;
background: grey
}
.new2 {
color: pink;
background: green
}
.new3 {
color: orange;
background: red
}
<div class='div1'>1</div>
<div class='div2'>2</div>
<div class='div3'>3</div>
<button>Click</button>
I am now creating several class and use classList.toggle() to switch between them, it absolutely work but the code looks so massy and I want to make my code more readably, what will a better solution for this kinds of situation.
I have thought of switching between with/without a specific css stylesheet, but I don't think it will work for my situation and I need to consider overwriting problem? (Correct me if I am wrong).
Could anyone suggest me an alternative and better solution of solving this situation like this where you have to assign lots of styles to multiple elements or is there an easy way?
*I know this is a stupid example and in this example, a possible solution is to use a forEach loop and use template literal for the className, but this is just a minimal example I created because of Stack overflow rule, so please don't blame me on this rough example. My actual code contains more different html tags and css styles I have to deal with. By storing them in a variable and keeping switching class between them is too messy and annoying.
My code looks something like this:
So here's what I recommend: You can use conditional styling to change everything in one place. Example:
.a {
/* one set of styles */
}
.b .a {
/* set a different set of styles */
}
This way, you can conditionally set class b on a higher level element (like document.body) and change all your styles automatically.
You can change the classes of the elements in a loop (assuming you have your css pre-formated). For example;
/**
* When the BUTTON with the id named 'clickMe' is click
* Select all the DIV elements
* Foreach DIV selected, if the DIV contains the 'old-class-name'; remove it.
* Add the new class name to the class-list of the selected DIV
*/
document.body.querySelector('#clickMe').addEventListener('click',()=>{
document.body.querySelectorAll('DIV').forEach((D,I)=>{
if(D.classList.contains('old-class-name')) D.classList.remove('old-class-name');
D.classList.add(`new-class-name-${I}`);
});
});
// List of CSS class names.
.new-class-name-0{
color: orange;
}
.new-class-name-1{
color: green;
}
.new-class-name-2{
color: blue;
}
<div class="old-class-name">Div 1</div>
<div class="old-class-name">Div 2</div>
<div class="old-class-name">Div 3</div>
<button id="clickMe">Click</button>

Can I add a classname to a CSS variable?

Is it possible to add a classname to a CSS variable or is there some other way to set it up so that I don't have to manipulate each individual variable directly via javascript? I'd like to keep all my styles in CSS and simply turn on relevant classes with JS. For example, If something like this was possible in CSS:
:root.white{ --bgcol:#FFF; --col:#000; }
:root.black{ --bgcol:#000; --col:#FFF; }
Then I could then just toggle the .black or .white class from javascript to trigger all vars to change. What's the best approach for this type of setup?
That's frankly the best (as in most idiomatic) approach — the use of class names, if not altogether separate stylesheets (as has been tradition for many, many years), to theme entire layouts via custom properties. It's the most "fundamentally CSS" approach with JavaScript merely being the glue that makes the theme switching work. You really can't do much better than that.
For those unaware what :root means and wondering where exactly the class names are being applied, it's the html element (the parent of body). So there is nothing special going on here — you're simply switching class names on the html element. It just happens that global custom properties are conventionally defined for the document root element since it's at the top level of the inheritance chain.
If you have any theme-agnostic custom properties, as well as style properties (i.e. not custom properties) that apply to the root element, keep them in their own unqualified :root rule, separate from your themed custom properties, so they won't be affected by theme switching. Here's an example:
const root = document.documentElement;
// Default theme - should assign declaratively in markup, not JS
// For a classless default theme, move its custom properties to unqualified :root
// Again, keep it separate from the other :root rule that contains non-theme props
// Remember, the cascade is your friend, not the enemy
root.classList.add('white');
document.querySelector('button').addEventListener('click', function() {
root.classList.toggle('white');
root.classList.toggle('black');
});
:root {
--spacing: 1rem;
color: var(--col);
background-color: var(--bgcol);
}
:root.white {
--bgcol: #FFF;
--col: #000;
}
:root.black {
--bgcol: #000;
--col: #FFF;
}
p {
margin: var(--spacing);
border: thin dashed;
padding: var(--spacing);
}
<button>Switch themes</button>
<p>Hello world!
Using :root selector is identical to using html, except its specifity is higher, thus there is no issues in using this approach.
For example:
:root {
--bg: red;
}
:root.blue {
--bg: blue;
}
// ...
div {
background: var(--bg);
}
Later, you should just change html's class and variables will change.
You can see an example in this fiddle.

Correct way to apply global styles into Shadow DOM

This questions is similar to some other on StackOverflow, but I couldn't find any answer describing applicable to my situation and non-deprecated method (and I'm starting thinking that maybe there is no any good solution for that situation).
Let's say we have some main.css file which includes common styles for buttons, lists, links and so on. So it's just some standard .css file which contains common styles that we want to reuse across the application. And we want to apply the same styles to Web Components with Shadow DOM.
There are a few ways, that I know about, to accomplish that:
Using one of deprecated approaches: ::shadow, >>>, /deep/ selectors. But those selectors are deprecated by now, so I guess it's not good approach to move forward with.
Using css variables. This approach is good for customization purposes, if we need to set a few properties. But it's too complex if we want to migrate 10-20 common styles from main.css file.
Using #import statement or "link" tags inside of Shadow DOM. It will work, but it will duplicate all styles for every component. If we have 10 web components we will end up with 10 duplicates of exactly the same styles. It doesn't sound like good enough solution too. Especially if we have a lot of common styles, sounds like it can be bad solution from performance point of view.
Don't use Shadow DOM at all and use global styles :) But it's not solution for current problem.
I also checked how the same problem resolved in Angular Framework (I checked version 5 of Angular). When I set encapsulation behavior to Native, it's just actually duplicating styles (like in #3 described above), what I think isn't the best way (but maybe the best currently existing way).
So, does anyone know if there is any other way to solve this problem without described above drawbacks? It just sounds like current drawbacks of Shadow DOM bring even more problems than it tries to solve.
There's no real drawback with solution 3:
Whether you apply a CSS style to n elements in a main document, or to 1 element in n Shadow DOM, the style will be duplicated to the whole n elements anyways.
If you import a document n times in n Shadow DOM, il will be actually be loaded only one time and reused through the browser cache.
After that, it will depend on the browser implementation of Shadow DOM and CSS styles, and you should see a performance degradation only the thousands of Shadow DOM.
2019 update for Chrome 73+ and Opera 60+
Now you can directly instanciate a CSSStyleSheet object and assign it to different Shadow DOMs.
This way the HTML won't be duplicated.
var css = new CSSStyleSheet()
css.replaceSync( "#import url( main.css )" )
host.shadowRoot.adoptedStyleSheets = [css]
host2.shadowRoot.adoptedStyleSheets = [css]
You can also apply it to the global document:
document.adoptedStyleSheets = [css]
The other advantage is that an update on the stylesheet will be applied to all Shadow DOMs (and document) that adopted it.
css.replaceSync( '.color { color: red }' )
I managed to do it using javascript modules but I doubt it's the cleanest solution.
You can create a GlobalStyles.js file that will contain the css styling that is common throughout various components. Changing the language mode on your editor to 'html' will provide syntax highlighting for the css.
const GlobalStyles = {
main: `
<style>
body {
overflow: hidden;
margin: 0;
font-family: 'Poppins';
}
h3 {
font-size: 39px;
}
</style>
`,
button: `
<style>
button {
display: block;
cursor: pointer;
outline: none;
font-family: 'Poppins Medium';
line-height: 17px;
padding: 9px 13px;
font-size: 15px;
background-color: #9f28d8;
color: white;
border: 2px solid;
border-radius: 5px;
border-color: #9f28d8;
width: max-content;
}
</style>
`
}
export default GlobalStyles;
Afterwards, you can import it into another js file that contains the code to the shadow dom of your custom element.
import GlobalStyles from './GlobalStyles.js';
const template = document.createElement('template');
template.innerHTML = `
${GlobalStyles.button}
<style>
ul {
font-family: Helvetica, Arial, sans-serif;
font-size: 13px;
width: 20em;
list-style-type: none;
}
</style>
<ul></ul>
<button>Click me</button>
`;
export class CustomList extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.appendChild(document.importNode(template.content, true));
}
}
The drawback with this approach is it only works if you are working purely with js files.

How to find all css classes and its css attributes inside a certain div?

i would like to find all classes and ids inside a certain div ! and these css attributes!
Example :
<div class="demo">
<div class="new_class">
<p id="para">This is Demo Paragraph</p>
<a style="background:#ccc">HyperLink</a>
</div>
</div>
<style>
.demo{
height:100px; width:100px; background:#FF0;
}
.new_class{height:40px; width:40px; background:#999;}
#para{color:#E1E1E1;}
</style>
Now The question is that: i would like to find all classes and ids which are used inside demo class ! and Their css values too(which style applying now. ).
I would like to find result as below :
<style>
.demo{
height:100px; width:100px; background:#FF0;
}
.new_class{height:40px; width:40px; background:#999;}
#para{color:#E1E1E1;}
a{background:#ccc;}
</style>
OP, not sure what your purpose is, but in general, this can be useful. I had a project where I needed to embed a fancy template from one site onto a page on a different site with a very different, and conflicting stylesheet. I used some code similar to the following to grab every applied style from the original content, via document.styleSheets, then reapplied them all as inline styles, so I could put it onto the "parent" site without the stylesheets conflicting.
Fiddle
JS
var selector,rule;
var result=[];
var sheets = document.styleSheets;
for (var i in sheets) {
//rules or cssRules, depending on the browser
var rules = sheets[i].rules || sheets[i].cssRules;
//iterate over every css rule in the document
for (var r in rules)
{
selector=rules[r].selectorText;
rule=rules[r].cssText;
//select demo itself, as well as all of its children
$('.demo, .demo *').each(function () {
//console.log($(this),selector);
//for each element, see if it matches the current rule. add if it does
if ($(this).is(selector))
{
result.push(rule);
}
});
}
}
console.log(result);
//result[0] .demo { height: 100px; width: 100px; background: none repeat scroll 0% 0% rgb(255, 255, 0); }
//result[1] .new_class { height: 40px; width: 40px; background: none repeat scroll 0% 0% rgb(153, 153, 153); }
//result[2] #para { color: rgb(225, 225, 225); }
Granted, you will have to tweak this on your own to do things like, removing duplicate styles that would occur if you were to apply this to a larger block of HTML, and for dealing with inline styles (which this does not attempt to do, but you can get them from the style attribute and work from there...), and possibly the computed style, which you can get with getComputedStyle, as indicated by the #Derek's answer. but this should get you started.
To find all existing id, try:
var ids = [];
$(".demo *").each(function(){ this.id && ids.push(this.id); });
console.log(ids);
Do the same thing for class or anything else.
However, to get your expected output, you must first acquire the defined CSS style for each element. Which one should be included? p by default gets margins and paddings. Do you include those too? You will also need to dig into all the CSS declarations just to find the style that are applied, which is almost impossible to do.
For example,
<div class="yellow"></div>
<style>
div.yellow:not(.blue){
background: yellow;
}
</style>
How do you get the background of the <div> tag? .style.background? Nah, it returns "". Well now you will have to reach into the CSS declaration with document.styleSheets to see which one applied. How do you even check if the rule div.yellow:not(.blue) matches your element? Good luck doing that. (There might be libraries that does this kind of thing, or maybe you can even utilize jQuery's internal selector engine with .is, though it will not be the same as in CSS) Another thing you can do is try getComputedStyle. It gives you every single computed styles that aren't even in your declaration. So what you are trying to do is not possible to do. (I don't even know what you are doing something like this.)

Applying css with javascript overrides hover link style?

I have some JavaScript which is changing an image correctly but once it has been called, my a:hover CSS code no longer works.
Looking with firebug the following JavaScript creates this css rule:
element.style {
background-image:url(/content/images/side_partnershipsOver.png);
}
document.getElementById('partnerships').style.backgroundImage = "url(/content/images/side_partnershipsOver.png)";
How can I apply the JavaScript and not have the a:hover code overriden by the element.style rule?
As far as I know setting the element.style.backgroundImage is essentially the same as using an inline style.
<style type="text/css">
a { background: blue; }
a:hover { background:green; }
</style>
<a href="#" style="background:red;">link<a>
Unfortunately the inline style always wins. In the above sample the link will always be red. As Daniel White said jQuery would be very useful here. Although you may be able to get around this issue in two ways.
One, Generate the style using javascript to write a style tag
document.write("<style type='text/css'>#partnerships { background-image:url(/content/images/side_partnershipsOver.png);}</style>");
or two, Manually setup mouseenter/mouseleave events to handle your hover style
Update
or three, as pointed out by KevinUK, use the !important css tag to override the inline style set.
<style type="text/css">
a { background: blue; }
a:hover { background:green !important; }
</style>
<a href="#" style="background:red;">link<a>
I was also frustrated about this CSS js style gap so I build
methods to apply style from js with a CSS string
elm.jCSS(cssText);elm.jCSSPseudo(cssText,pseudoElt)

Categories

Resources