Overriding style in different media size in React js - javascript

I am setting style for div element inline - it is a dynamically caluclated value in React component:
<div className={s.Tag} style={{ fontSize: `${newSize}px` }}></div>
However in module CSS I need to set this to different size:
.Tag {
font-size: 12px !important;
}
But in for certain screen sizes (custom-media) I want to use this style that is set inline for the font-size. I tried the following approach but it won't use the inline style from the div element itself
#media (min-width: 1366px) {
.Tag {
font-size: unset !important;
}
}
How can I reset the css style to use the inline style for certain media queries?

you should propably try to get rid of the !important keywords. it will override ALL previous styling rules for that specific property. unset on the other hand makes your div inherit the font-size from it's parent. and since it's !important it has precedence over the style attribute afaik.
a possible Solution in your component could be something like useEffect (get's executed on render) and useRef (creates a reference to the dom node) to then set a css custom property on that div.
const your_component = () => {
const ref = useRef(null);
useEffect(()=>{
ref.current?.setProperty('--size-font', `${newSize}px`);
})
return <div className={s.Tag} ref={ref}></div>
}
This will set a css custom property on your div when the component renders.
in your css you could then do:
#media (min-width: 1366px) {
.Tag {
font-size: var(--size-font);
}
}

Related

how to Unstyle html element? [duplicate]

Is there a CSS rule available that will remove any styles previously set in the stylesheet for a particular element?
A good use example might be in a mobile-first RWD site where much of the styling used for a particular element in the small-screen views needs 'resetting' or removing for the same element in the desktop view.
A CSS rule that could achieve something like:
.element {
all: none;
}
Example usage:
/* mobile first */
.element {
margin: 0 10;
transform: translate3d(0, 0, 0);
z-index: 50;
display: block;
etc..
etc..
}
#media only screen and (min-width: 980px) {
.element {
all: none;
}
}
So we could quickly remove or re-set styling without having to declare every property.
The CSS property all has a keyword initial that sets the CSS property to the initial value as defined in the spec. The all keyword has broad browser support except for the IE and Opera Mini families.
/* basic modern patch */
#reset-this-root {
all: unset;
}
or
#reset-this-root {
all: initial;
}
Since IE's lack of support may cause issue here are some of the ways you can reset some CSS properties to their initial values:
.reset-this {
animation : none;
animation-delay : 0;
animation-direction : normal;
animation-duration : 0;
animation-fill-mode : none;
animation-iteration-count : 1;
animation-name : none;
animation-play-state : running;
animation-timing-function : ease;
backface-visibility : visible;
background : 0;
background-attachment : scroll;
background-clip : border-box;
background-color : transparent;
background-image : none;
background-origin : padding-box;
background-position : 0 0;
background-position-x : 0;
background-position-y : 0;
background-repeat : repeat;
background-size : auto auto;
border : 0;
border-style : none;
border-width : medium;
border-color : inherit;
border-bottom : 0;
border-bottom-color : inherit;
border-bottom-left-radius : 0;
border-bottom-right-radius : 0;
border-bottom-style : none;
border-bottom-width : medium;
border-collapse : separate;
border-image : none;
border-left : 0;
border-left-color : inherit;
border-left-style : none;
border-left-width : medium;
border-radius : 0;
border-right : 0;
border-right-color : inherit;
border-right-style : none;
border-right-width : medium;
border-spacing : 0;
border-top : 0;
border-top-color : inherit;
border-top-left-radius : 0;
border-top-right-radius : 0;
border-top-style : none;
border-top-width : medium;
bottom : auto;
box-shadow : none;
box-sizing : content-box;
caption-side : top;
clear : none;
clip : auto;
color : inherit;
columns : auto;
column-count : auto;
column-fill : balance;
column-gap : normal;
column-rule : medium none currentColor;
column-rule-color : currentColor;
column-rule-style : none;
column-rule-width : none;
column-span : 1;
column-width : auto;
content : normal;
counter-increment : none;
counter-reset : none;
cursor : auto;
direction : ltr;
display : inline;
empty-cells : show;
float : none;
font : normal;
font-family : inherit;
font-size : medium;
font-style : normal;
font-variant : normal;
font-weight : normal;
height : auto;
hyphens : none;
left : auto;
letter-spacing : normal;
line-height : normal;
list-style : none;
list-style-image : none;
list-style-position : outside;
list-style-type : disc;
margin : 0;
margin-bottom : 0;
margin-left : 0;
margin-right : 0;
margin-top : 0;
max-height : none;
max-width : none;
min-height : 0;
min-width : 0;
opacity : 1;
orphans : 0;
outline : 0;
outline-color : invert;
outline-style : none;
outline-width : medium;
overflow : visible;
overflow-x : visible;
overflow-y : visible;
padding : 0;
padding-bottom : 0;
padding-left : 0;
padding-right : 0;
padding-top : 0;
page-break-after : auto;
page-break-before : auto;
page-break-inside : auto;
perspective : none;
perspective-origin : 50% 50%;
position : static;
/* May need to alter quotes for different locales (e.g fr) */
quotes : '\201C' '\201D' '\2018' '\2019';
right : auto;
tab-size : 8;
table-layout : auto;
text-align : inherit;
text-align-last : auto;
text-decoration : none;
text-decoration-color : inherit;
text-decoration-line : none;
text-decoration-style : solid;
text-indent : 0;
text-shadow : none;
text-transform : none;
top : auto;
transform : none;
transform-style : flat;
transition : none;
transition-delay : 0s;
transition-duration : 0s;
transition-property : none;
transition-timing-function : ease;
unicode-bidi : normal;
vertical-align : baseline;
visibility : visible;
white-space : normal;
widows : 0;
width : auto;
word-spacing : normal;
z-index : auto;
/* basic modern patch */
all: initial;
all: unset;
}
Relevant GitHub repo with a December 2017 more exhaustive list
Related
Related from MDN
Related W3C specs
With all this said, I don't think a CSS reset is something feasible unless we end up with only one web browser, if the 'default' is set by browser in the end.
The all property does this, and works like this:
CSS:
#someselector {
all: initial;
}
#someselector * {
all: unset
}
SCSS:
#someselector {
all: initial;
* {
all: unset;
}
}
Works in all major browsers that are still supported. Does not work in Internet Explorer, if you still have to maintain that.
Use all: revert or all: unset.
From MDN:
The revert keyword works exactly the same as unset in many cases. The
only difference is for properties that have values set by the browser
or by custom stylesheets created by users (set on the browser side).
You need "A CSS rule available that would remove any styles previously set in the stylesheet for a particular element."
So, if the element have a class name like remove-all-styles:
HTML:
<div class="remove-all-styles other-classe another-class">
<!-- content -->
<p class="text-red other-some-styles"> My text </p>
</div>
With CSS:
.remove-all-styles {
all: revert;
}
This will reset all styles applied by other-class, another-class and all other inherited and applied styles to that div.
Or in your case:
/* mobile first */
.element {
margin: 0 10;
transform: translate3d(0, 0, 0);
z-index: 50;
display: block;
etc..
etc..
}
#media only screen and (min-width: 980px) {
.element {
all: revert;
}
}
Will do.
If we want to isolate embedded widgets/components from the styles of the page that contains them, we could write:
.isolated-component {
all: revert;
}
Which will reverts all author styles (i.e. developer CSS) to user styles (styles which the user of our website sets - the less likely scenario) or to user-agent styles itself if no user styles set.
The quick answer is use "all:revert"
.element {
all:revert;
}
all:revert will RESET all the style properties on your element back to the original browser default UA style sheet property values, or whatever is styled in the parent body element. But it will not ERASE style properties like initial, returning them to a completely unstyled state.
In the case of text or inherited properties, "revert" resets your element's CSS property back to its inherited values coming from your "body" element or the browser's default UA style value, not to the property’s base style. For a non-inherited property, it resets it back again to the browser's UA default style sheet and not to the property’s base style. "all" allows all properties to be affected. This is likely what you want to see.
Problems Using "all:revert"
"all:revert" is a newer CSS declaration that only works in more modern HTML5 browsers (post-2015), and even then has very poor support in certain modern browsers like Internet Explorer 1-11, Edge Trident, and some mobile browsers. None of the older, non-HTML5 browsers (pre-2010) will understand this declaration, so it will be ignored by a wide range of browsers, old and new. (See my mixed CSS solution down below that has fixes for Internet Explorer).
Problems Using "initial" and "unset"
You can use "initial" or "unset" but you have to manually apply them for each property, and what is even worse, they will not return properties to the element's default display values as set by each browser's default UA style sheet, but "initial" will essentially erase the element's property values and create a completely unstyled element. For example, "display:block" on block level elements will be erased. Because the style property still needs a default value of some kind all block and non-block level elements with "display" will be changed to "display:inline" when you use "display:initial". You do not want to ever do this as it erases your styles AND the browser's default UA element styles from the selected element completely.
"unset" works close to the same, but in the case of inherited text-based CSS properties its properties inherit whatever is in the parents above the element (could be the browsers default UA style or whatever is in the HTML parent above), but for non-inherited properties works like "initial".
My recommendation is AVOID using all:initial or any form of initial in CSS unless you are trying to erase an individual CSS property you cannot erase in any other way. Why? initial erases not just the styles you applied but all styles the browsers default UA style sheet applied. all:revert will not do this. In terms of using initial, it does have better support in Internet Explorer, as does its cousin, inherit. But only IE8+ understands initial. So, there are a wide range of problems with this property value. It is not reliable.
The reason CSS works this way is all HTML elements come without any styling until the browser applies a default user-agent style sheet that gives all the HTML elements a base style. All HTML elements really have NO STYLES, and other than "replaced" elements like textarea and buttons, look alike until each browser's default UA sheet is applied. "initial" and "unset" would wipe away most of that from the browser. "revert" at least preserves their basic style set applied by the user's browser, and is therefore superior to "initial" and "unset". You can review all the various default style sheets that come with browsers in the link below.
A LIST OF DEFAULT BROWSER STYLE SHEETS:
https://meiert.com/en/blog/user-agent-style-sheets/
NOW FOR AN EVEN BETTER SOLUTION
There are two ideas here being confused:
The first idea is about "returning" styles back to a browser's UA style sheet value set (the style sheet that comes with the browser on install that defines what each element looks like). Each browser defines its own styles as to how elements should look by default. This idea is about returning all page styles back to each browsers native element styles.
The second idea is about "resetting" all default browser styles to a common look and feel shared by all browsers. People build special "reset" sheets to try and align all the browser elements to a common agreed on style, universally. This has nothing to do with a browsers default UA styles and more about "cleaning up" and aligning all browsers to a common base style. This is an additive process only.
Those are two very different concepts people here are confusing.
Because each browser often had default, out-of-the-box element and layout styles that looked slightly different, people came up with the idea of the "reset" or "reboot" style sheet to align all the browsers BEFORE applying custom CSS. Bootstrap now does this, for example. But that had nothing to do with people wanting to return to the browser's default look and feel.
The problem was not the building of these custom "reset" style sheets, it is figuring out what the default CSS was for each browser and each element BEFORE any styles were applied. Most found out you cant rebuild an existing clean cascade until you "clear out" all styles already applied. But how to get back to the default browser styling?
For some this meant going beyond returning the elements to the browsers UA style sheet that comes with the browser. Many wanted to reset back to "initial" property values which has NOTHING to do with the browser's default style, but really the properties defaults. This is dangerous as in the case of "display" pushes block level elements back to "inline" and breaks table layouts and other things.
So I do NOT agree with users here using "initial" to reset anything or custom reset classes that change every property back to some arbitrary base value set.
A better solution to me has always been to attempt to try and return all core element styling back to the browser's UA style sheet values, which is what all our end-users are using anyway. If you are creating a new website, you don't have to do this. You start with the browser's default styles and style over them. Its only after you've added third-party CSS products, or found yourself with complicated CSS cascades, that you want to figure out how to return to the browser default style sheet values.
For this reason, I'm for creating your own "reset" sheet to reset all the elements to one common style first that's shared by all old and new browsers as a first step. You then have a solid framework that's much easier to revert to without going back to the browser defaults. You are simply building on a reset common core set of element style values. Once build your own "reset" sheet, one that ADDS not ALTERS the browsers UA styles, you have a site that's very easy to modify.
The only problem remaining then is when you have a site that does NOT have such a reset sheet, or have that complex third party CSS and need to try and return to the browser UA styles. How do you do that?
I realize Internet Explorer has forced us too manually reset every property to get back to any sort of reset. But pushing those property values all back to "initial" destroys the browser UA style sheet values completely! BAD IDEA! A better way is to simply use "all:revert" for non-IE browsers on every element using a wildcard, and "inherit" only for a handful of inherited root-level properties found in the "html" and "body" elements that affect all inheriting children in the page. (see below). I'm NOT for these huge resets of properties using "initial" or going back to some imaginary standard we assume all browsers or IE will use. For starters "initial" has poor support in IE and doesn't reset values to element defaults, only property defaults. But its also pointless if you are going to create a reset sheet to align all elements to a common style. In that case its pointless to clear out styles and start over.
So here is my simple solution that in most cases does enough to reset what text-based values sift down into IE from the root and use "all:revert" for all non-IE browsers to force non-inherited values back to the browser's UA style sheet completely, giving you a true restart. This does not interfere with higher level classes and styles layered over your element styles, which should always be the goal anyway. Its why I'm NOT for these custom reset classes which is tedious and unnecessary and doesn't return the element to its browser UA style anyway. Notice the slightly more selective selectors below which would write over, for example, Bootstrap's "reboot" style values, returning them to the browser default styles. These would not reset element styles on elements for IE, of course, but for non-IE browsers and most inheritable text styling it would return elements in most agents to the UA style sheets that come with browsers:
:root, html {
display: block;
font-family: inherit;
font-size: inherit;
font-weight: inherit;
line-height: inherit;
-webkit-text-size-adjust: inherit;
-webkit-tap-highlight-color: inherit;
all: revert;
}
html body {
display: block;
font-family: inherit;
font-size: inherit;
font-weight: inherit;
line-height: inherit;
margin: inherit;
padding: inherit;
color: inherit;
text-align: inherit;
background-color: inherit;
background: inherit;
all: revert;
}
/* This rule attempts to manually reset all elements back to the
UA browser style sheet using "revert" and the "wildcard" (*)
which resets all properties on all HTML elements.
This would overwrite most of Bootstraps "reboot" styles
on elements, for example.
Note: This selector should be ignored by IE. */
html body * {
all: revert;
}
You can also use my free Universal CSS Framework which implements revert in it's reset style sheets.
The Problem
You need to insert markup into an HTML document, and it needs to look a specific way. Furthermore, you do not own this document, so you cannot change existing style rules. You have no idea what the style sheets could be, or what they may change to.
Use cases for this are when you are providing a displayable component for unknown 3rd party websites to use. Examples of this would be:
An ad tag
Building a browser extension that inserts content
Any type of widget
Simplest Fix
Put everything in an iframe. This has it's own set of limitations:
Cross Domain limitations: Your content will not have access to the original document at all. You cannot overlay content, modify the DOM, etc.
Display Limitations: Your content is locked inside of a rectangle.
If your content can fit into a box, you can get around problem #1 by having your content write an iframe and explicitly set the content, thus skirting around the issue, since the iframe and document will share the same domain.
CSS Solution
The best you can do is explicitly override all possible properties that can be overridden, and override them to what you think their default value should be.
Even when you override, there is no way to ensure a more targeted CSS rule won't override yours. The best you can do here is to have your override rules target as specifically as possible and hope the parent document doesn't accidentally best it: use an obscure or random ID on your content's parent element, and use !important on all property value definitions.
another ways:
1) include the css code(file) of Yahoo CSS reset and then put everything inside this DIV:
<div class="yui3-cssreset">
<!-- Anything here would be reset-->
</div>
2) or use
https://cssreset.com/scripts/vanilla-css-un-reset/
https://cssreset.com/scripts/html5-doctor-css-reset-stylesheet/
https://cssreset.com/scripts/eric-meyer-reset-css/
https://cssreset.com/scripts/tripoli-css-reset-david-hellsing/
https://cssreset.com/scripts/normalize-css/
If you happen to be using sass in a build system, one way to do this that will work in all the major browsers is to wrap all your style imports with a :not() selector like so...
:not(.disable-all-styles) {
#import 'my-sass-file';
#import 'my-other-sass-file';
}
Then you can use the disable class on a container and the sub-content won't have any of your styles.
<div class="disable-all-styles">
<p>Nothing in this div is affected by my sass styles.</p>
</div>
Of course all your styles will now be prepended with the :not() selector, so it's a little fugly, but works well.
I do not recommend using the answer that has been marked as correct here. It is a huge blob of CSS which tries to cover everything.
I would suggest that you evaluate how to remove the style from an element on a per case basis.
Lets say for SEO purposes you need to include an H1 on a page which has no actual heading in the design. You might want to make the nav link of that page an H1 but ofcourse you do not want that navigation link to display as a giant H1 on the page.
What you should do is wrap that element in an h1 tag and inspect it. See what CSS styles are being applied specifically to the h1 element.
Lets say I see the following styles applied to the element.
//bootstrap.min.css:1
h1 {
font-size: 65px;
font-family: 'rubikbold'!important;
font-weight: normal;
font-style: normal;
text-transform: uppercase;
}
//bootstrap.min.css:1
h1, .h1 {
font-size: 36px;
}
//bootstrap.min.css:1
h1, .h1, h2, .h2, h3, .h3 {
margin-top: 20px;
margin-bottom: 10px;
}
//bootstrap.min.css:1
h1, h2, h3, h4, h5, h6, .h1, .h2, .h3, .h4, .h5, .h6 {
font-family: inherit;
font-weight: 500;
line-height: 1.1;
color: inherit;
}
//bootstrap.min.css:1
h1 {
margin: .67em 0;
font-size: 2em;
}
//user agent stylesheet
h1 {
display: block;
font-size: 2em;
-webkit-margin-before: 0.67em;
-webkit-margin-after: 0.67em;
-webkit-margin-start: 0px;
-webkit-margin-end: 0px;
font-weight: bold;
}
Now you need to pin point the exact style which are applied to the H1 and unset them in a css class. This would look something like the following:
.no-style-h1 {
font-size: unset !important;
font-family: unset !important;
font-weight: unset !important;
font-style: unset !important;
text-transform: unset !important;
margin-top: unset !important;
margin-bottom: unset !important;
line-height: unset !important;
color: unset !important;
margin: unset !important;
display: unset !important;
-webkit-margin-before: unset !important;
-webkit-margin-after: unset !important;
-webkit-margin-start: unset !important;
-webkit-margin-end: unset !important;
}
This is much cleaner and does not just dump a random blob of code into your css which you don't know what it's actually doing.
Now you can add this class to your h1
<h1 class="no-style-h1">
Title
</h1>
In my specific scenario i wanted to skip applying common styles to a specific part of the page, better illustrated like this:
<body class='common-styles'>
<div id='header'>Wants common styles</div>
<div id='container'>Does NOT want common styles</div>
<div id='footer'>Wants common styles</div>
</body>
After messing with CSS reset which didn't bring much success (mainly because of rules precedence and complex stylesheet hierarchy), brought up ubiquitous jQuery to the rescue, which did the job very quickly and reasonably dirty:
$(function() {
$('body').removeClass('common-styles');
$('#header,#footer').addClass('common-styles');
});
(Now tell how evil it is to use JS to deal with CSS :-) )
If anyone is coming here looking for an answer that utilizes iframe here it is
<iframe srcdoc="<html><body>your-html-here</body></html>" />
https://caniuse.com/iframe-srcdoc
You mentioned mobile-first sites... For a responsive design, it's certainly possible to override small-screen styles with large-screen styles. But you might not need to.
Try this:
.thisClass {
/* Rules for all window sizes. */
}
#media all and (max-width: 480px) {
.thisClass {
/* Rules for only small browser windows. */
}
}
#media all and (min-width: 481px) and (max-width: 960px) {
.thisClass {
/* Rules for only medium browser windows. */
}
}
#media all and (min-width: 961px) {
.thisClass {
/* Rules for only large browser windows. */
}
}
Those media queries don't overlap, so their rules don't override each other. This makes it easier to maintain each set of styles separately.
For those of you trying to figure out how to actually remove the styling from the element only, without removing the css from the files, this solution works with jquery:
$('.selector').removeAttr('style');
BETTER SOLUTION
Download "copy/paste" stylesheet‎ to reset css properties to default (UA style):
https://github.com/monmomo04/resetCss.git
Thanks#Milche Patern!
I was really looking for reset/default style properties value. My first try was to copy the computed value from the browser Dev tool of the root(html) element. But as it computed, it would have looked/worked different on every system.
For those who encounter a browser crash when trying to use the asterisk * to reset the style of the children elements, and as I knew it didn't work for you, I have replaced the asterisk "*" with all the HTML tags name instead. The browser didn't crash; I am on Chrome Version 46.0.2490.71 m.
At last, it's good to mention that those properties will reset the style to the default style of topest root element but not to the initial value for each HTML element. ‎So to correct this, I have taken the "user-agent" styles of webkit based browser and implemented it under the "reset-this" class.
Useful link:
Download "copy/paste" stylesheet‎ to reset css properties to default (UA style):
https://github.com/monmomo04/resetCss.git
User-agent style:
Browsers' default CSS for HTML elements
http://trac.webkit.org/browser/trunk/Source/WebCore/css/html.css
Css specifity (pay attention to specifity) :
https://css-tricks.com/specifics-on-css-specificity/
https://github.com/monmomo04/resetCss.git
if you set your CSS within classes,
you can easly remove them using jQuery removeClass() Method.
The code below removes .element class:
<div class="element">source</div>
<div class="destination">destination</div>
  <script>
$(".element").removeClass();
</script>
If no parameter is specified, this method will remove
ALL class names from the selected elements.
I was using Material-Tailwind for my project and was struggling to remove the default css of an element. SO I simply added style={{all: "revert"}} as the attribute in my jsx and it worked for me.
As other answers have mentioned, the CSS property all set to the value unset seems to override all CSS properties without knowing which properties are in play. However, this did not work for me while adding custom CSS in a Wordpress site, as the all property was not recognized by the Wordpress custom CSS editor, and did not reflect changes in Microsoft Edge. Instead, what worked for me was a brute-force override, that is, to identify every property used in the webpage element and manually reset each one of them. The way to identify the CSS properties being used by an element is to inspect the element with your web browser, and go through the 'Styles' tab.
Any chance you're looking for the !important rule? It doesn't undo all declarations but it provides a way to override them.
When an !important rule is used on a style declaration, this declaration overrides any other declaration made in the CSS, wherever it is in the declaration list. Although, !important has nothing to do with specificity.
https://developer.mozilla.org/en-US/docs/CSS/Specificity#The_!important_exception

Styling a library component once it's been packaged?

How do we style library packaged component from via styles.scss?
For example suppose we have a <hello-component> and the template looks like this:
<div><h1 class="fs-HelloHeading">Hello!</h1><div>
How can be override the CSS inside fs-HelloHeading class and do it in a way that is context sensitive?
So for example if <hello-component> is inside <party-component> then it should have a yellow background, but if it's inside funeral-component then it should have a black background, and we would set these by overriding the styles in fs-HelloComponent. Thoughts?
My end goal is to override classes that are packaged with a component. For example I have these packaged with an Angular Material Table Component.
.mat-header-cell {
justify-content: left;
white-space: nowrap;
min-width: 12rem;
}
.mat-cell {
justify-content: left;
white-space: nowrap;
min-width: 12rem;
}
However I may want to change the width from outside the component later in a specific context, so I was thinking about doing that by adding additional css classes to the mat-row-element.
It is possible to override a style with the !important keyword. from top to bottom, the last !important will be applied. To set individual stylings depending on the surrounding element you can just 'mimic' the DOM-structure. Here is an example what you can put just on the end of the SCSS-file.
party-component {
hello-component {
background-color: yellow !important;
}
}
funeral-component {
hello-component {
background-color: black !important;
}
}
Please note that you have to replace colors and component-names with actual values.
Just try to define another custom selector with more or equal specificity to your CSS selectors.
if any rule is overridden,then you need to use !important flag to force your custom css rules, also consider that when you are using bootstrap, then some utilities classes have !important attribute.
<h1 id="custom-id" class="fs-HelloHeading">Hello {{ name }}!</h1>
style.css:
#custom-id {
color: blue;
}
you may want to use :host and ::ng-deep like
:host ::ng-deep .fs-HelloHeading { // in party-component css file
background-color: yellow;
}
:host ::ng-deep .fs-HelloHeading { // in funeral-component css file
background-color: black ;
}
it will look for all the child elements of these components
for more detail. Here's the docs: https://blog.angular-university.io/angular-host-context/

Is it possible to stop inheriting CSS within shadowDom from HTML tag?

Im injecting some Javascript that creates an isolated div located at the top of the body. Within this div there is a shadowDom element. The reason I went with shadowDom is because I thought it stoped CSS from bleeding in to all the divs within the shadowDom. But I can clearly see that it is inheriting style from the tag(font-size: 62.5%;). This is causing my text to be smaller. I can override this with adding font-size: 100% !Important but even though it crosses it out in the inspector tools it does not actually change. The only way I can get it to work is by unchecking the box in the CSS portion.
Please Help
Thanks,
Dev Joe
HTML Shadow Dom IMAGE
CSS Checked IMAGE
CSS Unchecked IMAGE
You should not use a relative font size (like 100%) because it applies to inherited size... so this will have no effect.
Insead, you should define a rule to the :host CSS peudo-class:
:host {
font-size: initial ;
}
NB: You'll need to add !important only if the font-size defined in the container (the main document) applies to the host element directly.
NB #2: You can use all: initial instead but you cannot combine it with !important.
host.attachShadow( { mode: 'open' } )
.innerHTML = `
<style>
:host { all: initial }
</style>
Inside Shadow Root <br>
<div>Div in Shadow DOM</div>
<slot></slot>
`
body { font-size : 62.5% ; color: red }
Small Font
<div>Div in main Document</div>
<div id=host>Light DOM</div>
No need for shadow dom, just use the all attribute to disable the inheritance.
#myElement {
all: initial;
}

Change auto generated CSS dynamically

Could you tell me how can I change the css dynamically? Here the problem is, the css has been generated by the framework itself. So I cannot declare or change it.
This is at runtime:
I need to pick swiper-pagination-bullets class and need to give bottom value conditionally. Like so:
Note: this is just pseudo:
If="data!=null" {
.swiper-pagination-bullets {
bottom: 190px !important;
}
}
else{
.swiper-pagination-bullets {
bottom: 150px !important;
}
}
Just like #Duannx mentioned in the comments, you could conditionally add a class in the ion-slides element, and then apply the css style rule to the pager based on that class.
<ion-slides pager="true" [class.with-data]="data" ...>
<ion-slide *ngFor="...">
<!-- ... -->
</ion-slide>
</ion-slides>
You'd need to change [class.with-data]="data" and replace it by the real property from your component, but then you could use it in the SCSS file to change the styles of the pager:
ion-slides.with-data .swiper-pagination-bullets {
bottom: 190px !important;
}
ion-slides:not(.with-data) .swiper-pagination-bullets {
bottom: 150px !important;
}
Instead of changing CSS dynamically, it would be better to override it instead by dynamically injecting a stylesheet into the page at runtime.
const style = document.createElement('style');
const bottom = condition ? 190 : 150;
style.insertRule(`.swiper-pagination-bullets { bottom: ${bottom}px; }`, 1);
document.head.appendChild(style);
I'd try to avoid using !important. If you inject a stylesheet in the manner shown above, it will already take precedence over the existing style due to it appearing later on the page, assuming the same selector specificity.
Or else you can try to artificially increase the specificity by doing .swiper-pagination-bullets.swiper-pagination-bullets (repeat as you deem fit). If that fails to work, then use !important.
Code for stylesheet injection taken from here.

Adding CSS media queries with javascript or jQuery

I'm having some issues trying to add media queries with jQuery/javascript. I have a <div class="container"> hidden on small screens with display: none. I want to use the code below to make it show up, although I don't get any errors nothing changes.
$('.container').append('<style type="text/css">#media screen and (min-width: 1012px){ .container { "display": "block"}}</style>');
Any suggestions? Thank you.
It's will work fine if you only delete double quotes form "display": "block"
$('.container').append('<style type="text/css">#media screen and (max-width: 1012px){ .container { display: block}}</style>');
but I think better if you change your selector
$('head').append('<style type="text/css">#media screen and (max-width: 1012px){ .container { display: block}}</style>');
You can use
document.querySelector('style').textContent +=
"#media screen and (min-width: 1012px){ .container { display: 'block'}}"
Get style element and add your new rules, and your html add if no exists
<style>......</style>
The answer of CMedina is quite good, but it appends to the first style element in the document. This could be problematic in two ways:
a) There might not be style element (because <link rel="stylesheet">);
b) There might be more than one style element. Appending style rules to the first one might be overwritten by later ones.
So here's my tactic:
create a new <style> element; fill with desired content; append to the body so it comes last
const styleSheet = document.createElement('style');
styleSheet.textContent = '#media print { /* ... */ }';
document.body.appendChild(styleSheet, 'beforeend');

Categories