combining same css style for 2 different browser - css

Is it possible to combine same style on different browser. I do understand that we could apply same css style for different tags like e.g
p , span{
background: red;
}
I would like to shorten my css code for
progress::-moz-progress-bar {
background:#cbccce;
}
progress::-webkit-progress-bar {
background:#cbccce;
}
this is what ive tried and but it seems not to be working.
progress::-moz-progress-bar , progress::-webkit-progress-bar {
background:#cbccce;
}
ve tried searching but i couldnt find an aswer. Thanks in advance :)

No, You cannot combine the "vendor prefixes" together.
But you can use developers tools to auto-generate them like autoprefixer or you can use CSS preprocessor SASS LESS to shorten your css code
What is a CSS preprocessor?
A CSS preprocessor is a scripting language that extends CSS by allowing developers to write code in one language and then compile it into CSS. Sass is perhaps the most popular preprocessor around right now, but other well-known examples include Less and Stylus.

Related

CSS remove unused styling

I often override "base" css styling by adding an (example) override.css below the base.css in the head of my sites.
base.css:
a { color: blue; }
And then later in override.css:
a { color: red; }
This might be bad practice, but in my experience a very common way of doing it in most websites. In this very simplified case the css-file would be double the size of what it could be.
Are there any automated tools to remove all unused styling, and only present a "parsed" css-file to the visitors? Would for example example CSS CCC option in Prestashop do this for me?
If you're looking for an automatic method, https://github.com/giakki/uncss
However, chrome devtools also includes a nice panel for seeing all unused styles, so most likely it's better to do it manually through this. How to use the coverage panel: https://blog.logrocket.com/using-the-chrome-devtools-new-code-coverage-feature-ca96c3dddcaf

Add prefixes to CSS class names using LESS or SASS

I am trying to use Bootstrap on a project that encompasses 400+ sites and uses the previous CSS class names (which I have no control over). I've been running into some CSS name clashing and the solution for me is to add a prefix to Bootstrap (.row to .tb-row for example).
I am familiar with the method of adding a namespace using LESS, where an additional class is wrapped around the classes. Unfortunately, this doesn't look like it will solve my issues.
Is there a method via LESS, SASS, or any other compiler that makes it easy for me to add a tb- prefix to all existing classes in Bootstrap?
You could probably do this with SASS
$namespace: "tb";
⌘ + f (or similar) to find all the classes in your CSS file. You're going to probably need a regex (and some trial+error) to find them all.
add .#{$namespace}- to all the classes.
Ideally, you'd get get something like this:
$namespace: "tb";
.#{$namespace}-myClass {
background:pink !important;
}
.#{$namespace}-carousel-module {
width: 25%;
}
compiled to
.tb-myClass {
background:pink !important;
}
.tb-carousel-module {
width: 25%;
}
"Easy" might be a stretch but "easier" seems fitting.
I'm not sure if this is the best approach, in honesty, I'm just ripping off a gist that I saw with comments from people a lot smarter than I am. May come in handy for you though!
You would need to modify the bootstrap code directly, an example of how this could be achieved elegantly in less:
.prefixname {
&-row {
...
}
}
I've added prefix "tb-" to all the bootstrap class (for LESS) in v3.1.0. So after you compile the less files you will get something like ".tb-btn"
You can fork my project at https://github.com/TimothyGuo/tb--prefix-for-Bootstrap-v3.1.0--LESS-

css compressor and factorization

I'm working with a friend on a project with a huge CSS file.
There is a lot of duplication like:
h1 {
color : black;
}
h1 {
color : blue;
width: 30px;
}
The first h1 can be removed, because it will never be used, because fully rewrited by the second. (because it is in the same CSS file)
I would know if it exists a tool that factorizes (and compress) this kind of stuff.
To only have at the end:
h1 {color:blue;width:30px}
PS: If it can be an online tool, it will be perfect!
There's a nice one in ruby: http://zmoazeni.github.io/csscss
In node.js: https://github.com/rbtech/css-purge
Both are very easy to use from command line.
This is also a nice once: http://cssmerge.sourceforge.net
And a plugin for Firefox: https://addons.mozilla.org/en-us/firefox/addon/css-usage
First you can try
CSS usage checker
Then Try these
CSS Compressor
Javascript Compressor
If you are using Firefox, you can use this addon which will help you achieve it.
https://addons.mozilla.org/en-us/firefox/addon/css-usage/
It creates a new css which tells you only used rules and sideline unused one. It also lets you export that css.

How to use sass to properly avoid embedding twitter bootstrap class names on HTML

I am working on a Rails project that is just starting. We want to use twitter bootstrap as a base for our styles, at the beginning we would simply use bootstrap's class names directly on the HTML code, just like is shown in bootstrap's documentation, but after reading the following posts:
Lessons learned in maintainable css
Please stop embedding Bootstrap classes in your HTML
it became clear why that's not the proper why to use bootstrap, so after some more readings:
Decouple Your CSS From HTML
smacss
among other, it seemed that using sass #extend was the proper way to avoid using bootstrap's class names, so instead of doing this:
<button type="submit" class="btn">Search</button>
we would do this:
<button type="submit" class="button">Search</button>
and our sass code would look like this:
.button {
#extend ".btn";
}
The problem with that approach, besides the bunch of extra selectors that will be added each time we extend a bootstrap class just to use a different name, is that in cases where bootstrap uses selectors like this:
.form-search .input-append .btn, .form-search .form-input-append .btn {
border-radius: 0 14px 14px 0;
}
the button won't get the right style because sass will not apply that same rule to our custom class name, I mean, sass is not doing this:
.form-search .input-append .btn, .form-search .input-append .button,
.form-search .form-input-append .btn, .form-search .form-input-append .button {
border-radius: 0 14px 14px 0;
}
So I wonder, is this the right way to avoid embedding bootstrap's class names into HTML, if so, how should I handle this problem (it happens frequently)? if not, what would be a better way to use custom class names but still get the styles from bootstrap.
I really appreciate your thoughts on this. Please keep in mind that I am just learning about overall web design (css, sass, less, html, js, etc.).
When you rename .btn to .button, you also should rename .form-search to .form-searchnew etc?
In that case your sass code in the example above should be something like:
.form-searchnew .input-appendnew .button {
extend(.form-search .input-append .btn);
}
Which make sense (i don't know sass) and results in the css you expect.
I think bootstrap is not about css only. Bootstrap is about css, html(structure) and javascript. Even when you separate css from html i would not easy to migrate to an other framework. Beside the css you will have to change the html structure and javascript call too.
Example migrate from Twitter's Bootstrap 2 to 3 (see: Updating Bootstrap to version 3 - what do I have to do?). I also wondered if you could migrate by extending the old classes to the new css (see: http://bassjobsen.weblogs.fm/migrate-your-templates-from-twitter-bootstrap-2-x-to-twitter-bootstrap-3/). After reading the migration guide, i think you couldn't.
Other solutions. Angular JS decouples Twitter's Bootstrap from javascript. Also in this case migrations does not seem to be painless see: Angular Dialog directives with Bootstrap 3
Maybe also read this post: http://www.jasonwong.org/post/45849350459/migrating-from-zurb-foundation-twitter-bootstrap-to. It refers to Bourdon and Neat.
Example from their website:
<!-- HTML markup for the section right below this code block -->
<section>
<aside>What is it about?</aside>
<article>Neat is an open source semantic grid framework built on top of Sass and Bourbon…</article>
</section>
// Enter Neat
section {
#include outer-container;
aside { #include span-columns(3); }
article { #include span-columns(9); }
}
// And the result is...
As they say: "it relies entirely on Sass mixins and does not pollute your HTML" which seems the way you're looking for.
I recommend you have a look at sass placeholder classes http://sass-lang.com/documentation/file.SASS_REFERENCE.html#placeholders in order not to bloath your css. Most likely you won't be using every single element included in bootstrap and placeholders only get written to your stylesheet if they are actually extended in your code.
Also, I think people tend to get confused about how css frameworks work and how decoupling css and html actually works.
For very large websites (or ones that you expect eventually to grow very large), where performance and css file size is crucial, some kind of OOCSS approach is your best bet. And this means inevitably that you have formatting code directly in your HTML.
If you can allow yourself to be a little less efficient and want your HTML clean, make sure to use semantic classes (examples for buttons: call-to-action, call-to-action-secondary, submit, btn-primary, btn-corporate-color, etc...)
Also remember to decouple your JS from CSS! use special classes for attaching behaviour (example js-submit, js-call-to-action, etc....)
Last but not least: don't plan for updating your css framework. These frameworks are meant to give you a headstart, not to be your overall design solution. Extend them, adapt them, make them your own, invest in design and create your own look in order to make your app unique.
If what makes you think of updating is a worry to keep up with standard changes, better use compass mixins.
Use #extend, but don't quote selectors:
.button {
#extend .btn;
}
Then you'll see that Sass extends related selectors too, like you want (.form-search .input-append .btn etc.).
… besides the bunch of extra selectors that will be added each time we extend a bootstrap class just to use a different name …
#extend works by copying selectors. If you don't want that, you can "extend" in HTML instead -- i.e. add Bootstrap's class names. :)
For being new to most of this, you're on the right track; the resources you've been reading are excellent. But, I think the concerns you have might not be justified:
...the button won't get the right style because sass will not apply that same rule to our custom class name...
In fact, I think you must be mistaken. According to the Sass documentation:
#extend works by inserting the extending selector (e.g. .seriousError) anywhere in the stylesheet that the extended selector (.e.g .error) appears.
See http://sass-lang.com/documentation/file.SASS_REFERENCE.html#how_it_works for the full code example.
Your original solution was actually correct. Use extends, but without the quotes:
.button {
#extend .btn; //no quotes
}
I tested this using your example, and it works correctly. Sass copies all the selectors with ".btn" and on those newly created selectors, it replaces ".btn" with ".button".
Also, if Sass produces too much duplication for your liking, don't worry about it (so long as you are following best practices as pointed out by the links you posted). Duplicate code is easily compressed if the server uses gzip or the equivalent; the client shouldn't notice any slower loading times, although it might take slightly longer to "unzip" the CSS. As for CSS selector speed, don't worry about that either; the only case where speed matters for selectors is on the JavaScript side, particularly with jQuery. For your Sass code, simply follow best practices for maintainability (notably, modularization as you are trying to do, i.e. SMACSS) and you'll be good to go.
The answers given by sam and tjklemz will help you resolve your immediate technical challenge, but it's possible to decouple your CSS and HTML even more. I'll give an example below, but keep in mind that this is just a quick example to demonstrate the power of mixins/extending CSS classes.
I'd also strongly recommend checking out the ZURB Foundation framework, as it is natively SASS, and designed with this style of development in mind.
For example:
<body>
<div id="my-header">
<h1>My Company</h1>
<h2>My Tagline</h2>
</div>
<div id="my-main">
<div class="my-widget">
<h1>Widget Title</h1>
<a>Widget Option 1</a>
<a>Widget Option 2</a>
</div>
</div>
</body>
With the accompanying SCSS:
//these examples wouldn't really work
//because bootstrap needs more markup
#my-header {
#extend .navbar;
}
#my-header h1 {
#extend .branding;
}
#my-main {
#extend .container;
}
//good example
.my-widget {
#extend .well;
#extend .hero-unit;
}
.my-widget a {
#extend .btn;
}

How can I define colors as variables in CSS?

I’m working on a CSS file that is quite long. I know that the client could ask for changes to the color scheme, and was wondering: is it possible to assign colors to variables, so that I can just change a variable to have the new color applied to all elements that use it?
Please note that I can’t use PHP to dynamically change the CSS file.
CSS supports this natively with CSS Variables.
Example CSS file
:root {
--main-color:#06c;
}
#foo {
color: var(--main-color);
}
For a working example, please see this JSFiddle (the example shows one of the CSS selectors in the fiddle has the color hard coded to blue, the other CSS selector uses CSS variables, both original and current syntax, to set the color to blue).
Manipulating a CSS variable in JavaScript/client side
document.body.style.setProperty('--main-color',"#6c0")
Support is in all the modern browsers
Firefox 31+, Chrome 49+, Safari 9.1+, Microsoft Edge 15+ and Opera 36+ ship with native support for CSS variables.
People keep upvoting my answer, but it's a terrible solution compared to the joy of sass or less, particularly given the number of easy to use gui's for both these days. If you have any sense ignore everything I suggest below.
You could put a comment in the css before each colour in order to serve as a sort of variable, which you can change the value of using find/replace, so...
At the top of the css file
/********************* Colour reference chart****************
*************************** comment ********* colour ********
box background colour bbg #567890
box border colour bb #abcdef
box text colour bt #123456
*/
Later in the CSS file
.contentBox {background: /*bbg*/#567890; border: 2px solid /*bb*/#abcdef; color:/*bt*/#123456}
Then to, for example, change the colour scheme for the box text you do a find/replace on
/*bt*/#123456
Yeeeaaahhh.... you can now use var() function in CSS.....
The good news is you can change it using JavaScript access, which will change globally as well...
But how to declare them...
It's quite simple:
For example, you wanna assign a #ff0000 to a var(), just simply assign it in :root, also pay attention to --:
:root {
--red: #ff0000;
}
html, body {
background-color: var(--red);
}
The good things are the browser support is not bad, also don't need to be compiled to be used in the browser like LESS or SASS...
Also, here is a simple JavaScript script, which changes the red value to blue:
const rootEl = document.querySelector(':root');
root.style.setProperty('--red', 'blue');
CSS itself doesn't use variables. However, you can use another language like SASS to define your styling using variables, and automatically produce CSS files, which you can then put up on the web. Note that you would have to re-run the generator every time you made a change to your CSS, but that isn't so hard.
You can try CSS3 variables:
body {
--fontColor: red;
color: var(--fontColor);
}
There's no easy CSS only solution. You could do this:
Find all instances of background-color and color in your CSS file and create a class name for each unique color.
.top-header { color: #fff; }
.content-text { color: #f00; }
.bg-leftnav { background-color: #fff; }
.bg-column { background-color: #f00; }
Next go through every single page on your site where color was involved and add the appropriate classes for both color and background color.
Last, remove any references of colors in your CSS other than your newly created color classes.
The 'Less' Ruby Gem for CSS looks awesome.
http://lesscss.org/
Yes, in near future (i write this in june 2012) you can define native css variables, without using less/sass etc ! The Webkit engine just implemented first css variable rules, so cutting edge versions of Chrome and Safari are already to work with them. See the Official Webkit (Chrome/Safari) development log with a onsite css browser demo.
Hopefully we can expect widespread browser support of native css variables in the next few months.
Do not use css3 variables due to support.
I would do the following if you want a pure css solution.
Use color classes with semenatic names.
.bg-primary { background: #880000; }
.bg-secondary { background: #008800; }
.bg-accent { background: #F5F5F5; }
Separate the structure from the skin (OOCSS)
/* Instead of */
h1 {
font-size: 2rem;
line-height: 1.5rem;
color: #8000;
}
/* use this */
h1 {
font-size: 2rem;
line-height: 1.5rem;
}
.bg-primary {
background: #880000;
}
/* This will allow you to reuse colors in your design */
Put these inside a separate css file to change as needed.
Sure can, sort of, thanks to the wonderful world of multiple classes, can do this:
.red {color:red}
.blackBack {background-color: black}
but I often end up combining them anyway like this:
.highlight {color:red, background-color: black}
I know the semantic police will be all over you, but it works.
I'm not clear on why you can't use PHP. You could then simply add and use variables as you wish, save the file as a PHP file and link to that .php file as the style sheet instead of the .css file.
It doesn't have to be PHP, but you get what I mean.
When we want programming stuff, why not use a programming language until CSS (maybe) supports things like variables?
Also, check out Nicole Sullivan's Object-oriented CSS.
You can group selectors:
#selector1, #selector2, #selector3 { color: black; }
You could pass the CSS through javascript and replace all instances of COLOUR1 with a certain color (basically regex it) and provide a backup stylesheet incase the end user has JS turned off
dicejs.com (formally cssobjs) is a client-side version of SASS. You can set variables in your CSS (stored in json formatted CSS) and re-use your color variables.
//create the CSS JSON object with variables and styles
var myCSSObjs = {
cssVariables : {
primaryColor:'#FF0000',
padSmall:'5px',
padLarge:'$expr($padSmall * 2)'
}
'body' : {padding:'$padLarge'},
'h1' : {margin:'0', padding:'0 0 $padSmall 0'},
'.pretty' : {padding:'$padSmall', margin:'$padSmall', color:'$primaryColor'}
};
//give your css objects a name and inject them
$.cssObjs('myStyles',myCSSObjs).injectStyles();
And here is a link to a complete downloadable demo which is a little more helpful then their documentation : dicejs demo
EDIT: This answer is no longer current. You should use CSS variables now.
Consider using SCSS. It's full compatible with CSS syntax, so a valid CSS file is also a valid SCSS file. This makes migration easy, just change the suffix. It has numerous enhancements, the most useful being variables and nested selectors.
You need to run it through a pre-processor to convert it to CSS before shipping it to the client.
I've been a hardcore CSS developer for many years now, but since forcing myself to do a project in SCSS, I now won't use anything else.
If you have Ruby on your system you can do this:
http://unixgods.org/~tilo/Ruby/Using_Variables_in_CSS_Files_with_Ruby_on_Rails.html
This was made for Rails, but see below for how to modify it to run it stand alone.
You could use this method independently from Rails, by writing a small Ruby wrapper script
which works in conjunction with site_settings.rb and takes your CSS-paths into account, and
which you can call every time you want to re-generate your CSS (e.g. during site startup)
You can run Ruby on pretty much any operating system, so this should be fairly platform independent.
e.g. wrapper: generate_CSS.rb (run this script whenever you need to generate your CSS)
#/usr/bin/ruby # preferably Ruby 1.9.2 or higher
require './site_settings.rb' # assuming your site_settings file is on the same level
CSS_IN_PATH = File.join( PATH-TO-YOUR-PROJECT, 'css-input-files')
CSS_OUT_PATH = File.join( PATH-TO-YOUR-PROJECT, 'static' , 'stylesheets' )
Site.generate_CSS_files( CSS_IN_PATH , CSS_OUT_PATH )
the generate_CSS_files method in site_settings.rb then needs to be modified like this:
module Site
# ... see above link for complete contents
# Module Method which generates an OUTPUT CSS file *.css for each INPUT CSS file *.css.in we find in our CSS directory
# replacing any mention of Color Constants , e.g. #SomeColor# , with the corresponding color code defined in Site::Color
#
# We will only generate CSS files if they are deleted or the input file is newer / modified
#
def self.generate_CSS_files(input_path = File.join( Rails.root.to_s , 'public' ,'stylesheets') ,
output_path = File.join( Rails.root.to_s , 'public' ,'stylesheets'))
# assuming all your CSS files live under "./public/stylesheets"
Dir.glob( File.join( input_path, '*.css.in') ).each do |filename_in|
filename_out = File.join( output_path , File.basename( filename_in.sub(/.in$/, '') ))
# if the output CSS file doesn't exist, or the the input CSS file is newer than the output CSS file:
if (! File.exists?(filename_out)) || (File.stat( filename_in ).mtime > File.stat( filename_out ).mtime)
# in this case, we'll need to create the output CSS file fresh:
puts " processing #{filename_in}\n --> generating #{filename_out}"
out_file = File.open( filename_out, 'w' )
File.open( filename_in , 'r' ).each do |line|
if line =~ /^\s*\/\*/ || line =~ /^\s+$/ # ignore empty lines, and lines starting with a comment
out_file.print(line)
next
end
while line =~ /#(\w+)#/ do # substitute all the constants in each line
line.sub!( /#\w+#/ , Site::Color.const_get( $1 ) ) # with the color the constant defines
end
out_file.print(line)
end
out_file.close
end # if ..
end
end # def self.generate_CSS_files
end # module Site
Not PHP I'm afraid, but Zope and Plone use something similar to SASS called DTML to achieve this. It's incredibly useful in CMS's.
Upfront Systems has a good example of its use in Plone.
If you write the css file as an xsl template, you could read color values from a simple xml file. Then create the css with an xslt processor.
colors.xml:
<?xml version="1.0"?>
<colors>
<background>#ccc</background>
</colors>
styles.xsl:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" version="1.0" encoding="iso-8859-1"/>
<xsl:template match="/">body {
background-color: <xsl:value-of select="/colors/background" />;
}
</xsl:template>
</xsl:stylesheet>
Command to render css: xsltproc -o styles.css styles.xsl colors.xml
styles.css:
body {
background-color: #ccc;
}
It’s not possible with CSS alone.
You can do it with JavaScript and LESS using less.js, which will render LESS variables into CSS live, but it’s for development only and adds too much overhead for real-life use.
The closest you can come with CSS is to use an attribute substring selector like this:
[id*="colvar-"] {
color: #f0c69b;
}
and set the ids of all your elements that you want to be adjusted to names starting with colvar-, such as colvar-header. Then when you change the color, all the ID styles are updated. That’s as close as you can get with CSS alone.

Resources