How to Prevent Css applying to other Files? - javascript

In this React Component I have Cookbook.js and Cookbook.css. I have a bunch of styles in Cookbook.css and specifically it has
form {
display: inline-block !important;
padding-top: 30px;
margin-left: 100px;
}
Which is fine since I import that into the Cookbook.js. But I created another Component called Survey.js along with Survey.css. In Survey.js I use a form as well but I ONLY import survey.css. Yet for some reason, The CSS from Cookbook.css gets applied to the form in my Survey.js. As a result, my form on Survey.js is in a odd spot. How Can I ensure that the css for each form is independent of each other?

When you create CSS rules, it is often easier to use class names instead of id's. Such as:
.class {
background-color: blue;
}
When you have common elements across multiple components, the CSS color will apply the styling to all elements such as:
p {
background-color: blue;
}
If you want to differentiate the styling where it applies in one component but does not apply to another which I think you are trying to do in your case, you need to use id's instead of element or class names.
Add an id to the component that you want to style and create a rule for that element such as:
#hero {
background-color: bluel;
}
This should be able to ensure that CSS is different from each other.

I think that you are looking for CSS modules. CSS modules are CSS files that only apply to a single component. Here is an example: https://css-tricks.com/css-modules-part-1-need/. More about CSS modules can also be found on Google and other forums.
Thank you,
Caiden Sanders.

In React when a component is mounted, its specific CSS file is also imported. You should know that React makes only a single HTML page application. In one HTML page if you import multiple CSS files and if they have conflicting CSS, then CSS will be applied on the basis of priority.
CSS that comes last overrides existing if common elements conflicting unless you haven't used !important with any property.
So, you should use unique ids or classes to prevent conflicts wherever required, and use common CSS if you have similar behaviour for certain elements.

Related

How can I disable all CSS that can affect my widgets on another website?

I'm building JavaScript widgets that are supposed to be added onto other people's websites.
I style my widgets by dynamically adding a CSS to the pages they're on.
For example,
My CSS code below applies to a DIV inside my widget:
.myWidget { background-color: red; }
But a CSS file outside my own on a remote page might have:
div { border: 5px solid green; }
The CSS above would also apply to my widgets. How can I disable all other CSS outside my own?
Thanks
You could be Using shadow DOM
Shadow DOM MDN Web Docs
An important aspect of web components is encapsulation — being able to keep the markup structure, style, and behavior hidden and separate from other code on the page so that different parts do not clash, and the code can be kept nice and clean. The Shadow DOM API is a key part of this, providing a way to attach a hidden separated DOM to an element.
You can use the all shorthand property and the unset keyword to set each property's value to its initial value.
.myWidget {
all:unset;
background-color: red;
}
div {
background-color:yellow;
}
<div class="myWidget">Hello World!</div>

How to I apply a custom style for a third-party component in a single React component without affecting its style in other components?

I am using a dropdown from react-bootstrap and its context-menu has a className called Select-menu-outer. I wanted to change the font size of this menu only in one component.
What I did was, I just created a new css file called panel.css and did import './panel.css; in my component.
In the panel.css, I applied the style to the Select-menu-outer like
.Select-menu-outer { font-size: 12px }
This worked fine, but it affected the font size of all other dropdowns in the entire app.
I would have used CSS Modules and do something like import style from './panel.css and do className={style.Select-menu-outer} something like that, but since this is a third-party library component, I wasn't sure if I can do that.
Any good way to make this work?
Add a new class list to the drop down you what to change called .Select-menu-outer-size
Then do this in your css:
.Select-menu-outer-size { font-size: 12px !important}
The !important overrides the other class.
Javascript could be used!
let's say that it is the 3rd dropdown on that page with this class: .Select-menu-outer
So we do:
var addclass = document.getElementsByClassName("Select-menu-outer").[2];
addclass.classList.add("Select-menu-outer-size");
Then add you css:
.Select-menu-outer-size { font-size: 12px !important}
Note: 0 is 1 and 1 is 2 etc. for document.getElementsByClassName("Select-menu-outer").[2];
Linkhttps://www.w3schools.com/jsref/tryit.aspfilename=tryjsref_document_getelementsbyclassname
You can use the bsPrefix prop to customize the class of your component, in order to style it via CSS.
Change the underlying component CSS base class name and modifier class names prefix. This is an escape hatch for working with heavily customized bootstrap css.
Source: React-Bootstrap docs
You can use inline-styles on that specific menu to override the default style.
OR
you can assign an id e.g. id="outer-menu" to that specific menu tag and access that menu with #outer-menu in CSS.
The priority of id is greater than className so it will probably override it.

Change CSS theme in Angular

Im currently working on a Angular2 application with webpack and Im trying to set differents css themes according to the user.
For example : When the user connect, If it's a boy, I want to have my backgrounds blue, and if it's a girl I want the backgrounds to be pink.
Simply changing the css value with setAttribute or style.property wont work because the DOM is destroyed when changing tab in the application, it needs to be kinda permanent.
I've tried using different css stylesheets (1 for each theme) and linking them to my html with javascript when the user connect. Problem is, webpack is always adding automatically my css to my html when building the app.
Thanks for the help.
In your css, make a rule like :
.is-boy{
background: blue;
}
.is-girl{
background: pink;
}
and declare in you angular app a scope var like $scope.userSex = 'boy';
and on your body use ngClass like this
<body [ngClass]="{'is-boy': userSex === 'boy', 'is-girl': userSex === 'girl'}" ...
:host-context selector
You could use the :host-context selector to apply styles to your component based on the parent component.
styles:[`
:host-context(.parent1) div{
border: 1px solid blue;
}
:host-context(.parent2) div{
border: 1px solid blue;
}
`]
This allows you to conditionally apply styles based on a the selector that wraps the component.
plunker
edit:
So in your case - your parent would have a div with class .boy and a div with class .girl
You could load these containing divs with some flag controlled by ngIf
If you want to be permanent store class value in localStorage. To set the theme use ngClass with variable set to theme you need.

Proper way to isolate all elements under an element from external styles of project

I just included a new js calendar in my project. The calendar displays like this -
<div style="position: absolute;" id="container">
<table cellspacing="0" cellpadding="0" align="center" class="DynarchCalendar-topCont">
<tbody>
<tr><td>
// lots of elements inside
<td><tr>
</tbody>
</table></div>
The problem is that the view of the calendar is appearing distorted due to some styles in my project like this -
div#sel_filters div.fields div {
margin-left: 10px;
}
div.filters div.fields div {
float: left;
padding: 7px 0 0;
}
... and many more which apply to the elements inside
There are many css files of the project. Since my calendar appears inside div.fields, the above styles apply to it as well. I am not considering altering the above project styles , as they may affect others.
What is the proper clean way of not allowing any styles other than those in the jscalendar.css file to affect it. DO I only have this option of applying !important to the styles in the jscalendar.css, and searching all the extra attributes, which are only set by project css, and setting them 0 or null manually.
In case it matters, I am free to include the jscalendar.css before/after project css files.
If you load your jscalendar.css after the other CSS files it should overwrite the other CSS directives.
If you still have problems, you could add a class to the divs that should behave differently and then add a CSS directive after the others to overwrite the previous ones:
div.filters div.fields div.yourClass {
float: none;
padding: 0;
margin: 0;
}
The proper way to do this unfortunately is to fix your site's CSS. What you're doing by applying styles to elements directly such as div's is going to lead to a world of pain for future maintenance or changes.
Avoid styling elements directly at all costs, use classes as much as possible, then IDs. Use elements with classes or IDs like div.foo or div#foo but not elements directly.
You could get away with !important in your calendar CSS for now but I'd spend that time fixing your site's CSS, as if ever you upgrade the calendar plugin you're looking at painful times again.
So take the hit now, look at the positive of having learnt how to do things properly and never repeat the same mistake again :)
apply a unique id to the container and change your CSS to reflect the heritage that derives from that... direct styling will get you to where you wanna go, but its gonna cost you in the long run if you have to maintain this later down the road...
but i must agree with Moin Zaman, if you hit this obstacle, its bound to happen again if you dont take care of it right now

Naming conventions for html/css + MVC?

Are there any good articles on naming comprehensive naming conventions?
I'm looking to clean up some code... everything from assets to models (Codeigniter) to HTML and CSS.
I'm also curious how to structure the CSS... is it better to give everything a unique class ie search-bar-icon or is it better to repeat classes like .search span.icon {?
Thanks,
Walker
In HTML/CSS, the id and class selectors are not equivalent. The id carries more weight, so it should be used sparingly. Use it for sections of a page where you have descendant selectors whose class names are the same as other sections but you wish them to be styled differently. Think of the id like a poor man's namespacing for page regions.
Giving each thing a unique id makes your selectors fastest, but bloats your markup and can become a bog to work with. Using unique classes kind of doesn't make sense (classes are used for groups of objects).
Your second option is the cleaner code wise but the selectors are usually significantly slower.
Giving literally everything a unique class in your CSS defeats the purpose of "Cascading" style sheets. Effective CSS leverages the cascade so that you're repeating as little styling effort as possible.
Bear in mind that most HTML elements can be styled directly. I don't need to use <span class="something"><label>... because I can style the label itself without using a span. Most people use far more divs and spans than they really need to.
You can also style by inference. For example, I might have an <H3 class="searchResults"> followed by a UL of search results that I want to style uniquely from other ULs on the page. Instead of giving the UL a specific class (of, say, "searchResultsList") I could just use the following rule:
H3.searchResults + ul {some styling...;}
or
H3.searchResults + div > * {some styling...;}
As for CSS organization, I find it helpful to organize my files by categories of elements, starting with the simplest and most ubiquitous cases, like a, p, etc. and then handle more complex elements like tables later. I group everything by specificity, because that's part of the cascade rules. An element is handled first in its order of appearance in the file, and then by how specific a rule affecting it is. I place all my one-instance and utility classes last (.iconWhichAppearsOnceEver, .noBordersTable, etc.)
body{}
a {}
p {}
h1,h2,h3,h4,h5,h6 {}
h3.searchResults {}
...
table {}
thead {}
thead th {}
thead th a {}
thead th.noFill a {}
...
It fully depends on what you think is best. Conventions aren't rules, they're guidelines that can make your life easier. Codeigniter has relatively strict naming conventions due to the way it loads all the required classes.
For example, the filename of a controller is lowercase but the classname is capitalized and should match the filename. E.g. test.php would results in a class named Test.
Naming HTML classes/IDs is something that isn't standardised and fully depends on what you think is best. I usually try to give my IDs and classes a name that makes sense. For example, a DIV containing a logo will be named "site_logo". A DIV containing a blog article will be named "article", and so on.
Also, don't let the whole "IDs/classes are slower" thing fool you as the speed increase is very small. If you want to optimize your website you'd be better off optimizing your PHP or CSS code than removing HTML IDs or classes.
Remember that you can stack and inherit CSS classes, as follows:
.icon { background: left center no-repeat; padding-left: 20px; /* leave space for icon */
#SearchBar .icon { background-image: url(../images/icons/search.png); }
A nice technique I've used before is setting multiple CSS classes (in this case, for displaying an audit log):
/* the icon is displayed by each entry; if it has no other class,
it will show a "generic" icon */
.log .entry {
padding-left: 20px; /* leave space for icon */
background: url(../images/icons/log-generic.png) top left no-repeat;
}
/* slot a generic delete icon in */
.log .icon.delete {
color: red;
background-image: url(../images/icons/log-delete.png);
}
.log .icon.delete.person {
background-image: url(../images/icons/log-delete-person.png);
}
This is a great way to define a series of generic styles (for links with icons, toolbar buttons, avatars, etc), which you can then override in specific instances (think of it as class inheritance).
I'm a bit weird about naming in CSS, but I stick to the convention that UpperCase is for IDs, and lowerCamel for classes. It just helps me to differentiate.
The zen of CSS naming that I follow is:
The fewer IDs, the better
IDs should be reserved for main layout sections
...and to identify elements for DOM/AJAX operations
Use generic class names (log, icon, person, button, etc)
...then combine them with IDs or parent classes to form specifics, e.g. #Header a.icon.person for a profile link in the header
Most importantly, keep it lean. The less CSS, the better - use generic, re-usable styles, and you will benefit from a) consistency in your UI, and b) less page bloat.
HTH
The entire point of working with classes is so you can use them several times. For CSS specificly for a certain element you should use id's. As said, the less CSS code the better.

Categories