Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I’ve been trying to find out various ways to manage my CSS files which become bigger and bigger as time progresses. This has a few reasons: creating websites using responsive design, plugins that require additional styling or just page-specific styling for a single element.
There are a few techniques I’m already using, like:
Creating a table of contents
Separating code into named sections (to be referred in the table of contents)
Name-spacing the elements (.home-gallery, .home-gallery-image, .home-gallery-link etc.)
Yet there’s still the issue of how to lay down the properties for each element.
Putting everything in a single line significantly decreases the readability. On the other hand, putting each and every property in a single line makes my scrollbar go sit under a shower and cry.
I’m currently experimenting with some different forms, and here’s what I came up with:
Sorting and organizing properties according to their types
Using tabulation/spacing to create a sort of table-look (captions on the left: elements; contents on the right: properties)
In an example it looks as follows:
#content-wrapper {
position: relative; top: 0; left: 0;
width: 100%; height: 200px;
color: #333; background: #fff;
}
For now it seems to me, like the only compromise between having to scroll endlessly/searching for a piece of code and making it less-readable.
So my question is: What CSS writing techniques do you use that allow for good readability and further development?
1) I define style in the order of elements in the HTML
eg: html{ } head{ } body{ } likewise in the order. So while scrolling it will be easy to locate an element for me.
2) Writing styles in the order of screen width, if media query is included. From higher screen width to lower one. Which helps me to find the styles written for media elements easily. There also I follow the first point.
3) Format styles. It is almost like you did.
4) Keeping a documentation.
sample below:
/* indented multi-selectors */
#content-wrapper
, #content-wrapper > something else {
/* alphabetic listing of properties, organizing attributes in blocks */
background-color: #fff;
border-left-width: 2px; /* column layout with blockwise different positioning */
/* separation of blocks */
color: #333;
height: 200px;
left: 0;
position: relative;
top: 0;
width: 100%;
}
probably more important than formatting and organization of individual properties is a clean structure based on conspiring classes and proper documentation, especially of the rules' sequencing (it certainly has been in my projects. often the other way round ... ;-).
imho a decent folding editor sufficiently mitigates the need of frequent scrolling. and large screens, of course.
Related
I need to target divs that takes up more than 80% of their parent div, for a progress bar. Considering that we can target a specific width with CSS:
[data-width=80]
How might we target a comparison? This did not work in Firefox or Chrome:
[data-width>=80]
A google search for css comparison operators surprisingly did not turn up anything useful or relevant.
Note that I am targeting a data-* property, which I set together when setting the width in Javascript. Obviously I could just have the Javascript write an over80 class and target that, but there are additional concerns for which I need the targeting done in CSS. For one reason, it is the designer's job to decide at which width the change occurs. For another reason, we are targeting multiple devices, not just desktop web browsers.
Here is the target HTML and the CSS:
<div id='progress-bar-outer'>
<div id='progress-bar-inner'><span id='percent-indicator'>60%</span></div>
</div>
#progress-bar-outer {
overflow-y: auto;
height: auto;
border: #2072a7 solid 3px;
position: relative;
}
#progress-bar-inner {
float: left;
height: 25px;
background-color: #2072a7;
width: 60%;
}
#progress-bar-inner[data-width<80] {
position: relative;
}
#percent-indicator {
position: absolute;
top: 5px;
right: 10px;
}
This is a frequently-asked question, but the answer remains the same: CSS does not provide attribute selectors with numeric operations.
None of the existing attribute selectors work with any sort of value semantic; they only look at values as raw strings, and so only rudimentary string-matching attribute selectors exist at most. The next Selectors specification, Selectors 4, does not appear to introduce any numeric value attribute selectors either, but since it's still in its early stages of development, you could propose this feature if you're able to provide some good use case examples.
On a somewhat related note, the given example [data-width=80] is invalid precisely because tokens starting with a digit are interpreted in CSS as either numeric values or dimensions, and CSS attribute selectors only accept either a string or an identifier in the value component, not a number or dimension. If such a feature makes it to Selectors 4, this restriction may be lifted.
And if we're going to talk about separation of concerns, one could argue that setting a data attribute for a presentational value such as width, especially for the sake of RWD, is questionable in itself. The most sensible solution to this problem would be element queries, which don't exist as yet (as far as I've heard, it's primarily because they're difficult to implement correctly).
At this point, your best bet is in JavaScript, really.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
In the following article I read that one should try reduce the number of selecetors.
Article: use less selectors
I'm wondering if writing LESS and I'm using a lot of nesting to group parent and child elements, will that generate bad CSS code in the end?
LESS
.wrap{
width: 100%;
height: 20%;
background: green;
header{
background: blue;
h1{
color: red;
}
}
}
I'm using a lot of nesting to group parent and child elements, will that generate bad CSS code in the end?
In a word, yes. In the long run this will give you highly specific, unmaintainable CSS. Let 's have a look at what your example will produce for the h1 style.
.wrap header h1{ color: red; }
So what you've ended up with here is a very specific CSS selector, that isn't really necessary. You could, for instance, just have
h1 { color: red; }
or use a class on the h1
.title { color: red; }
Why is specificity bad?
So imagine, 6 months later another developer comes along and they need to change the color of a h1, but just one of them.
First they try to add a class to the h1
.new-color { color: blue; }
But the colour doesn't change because the original CSS is so specific. So they have to do this
.wrap header h1.new-color { color: blue }
or worse still they may do this
.new-color { color: blue!important; }
And then what happens when other changes need to be made? As you can see very quickly and very easily you can end up with unmaintainable CSS, that will have everyone pulling their hair out.
Performance
People usually negate performance when it comes to CSS, but it is always good to know what is going on when a page is rendered. CSS is read from right to left. Using your example
.wrap header h1 { color: red; }
This means the browser engine will search for every h1 and check if they have a parent header and then if that has a parent class wrap. If so it will apply the style. A low specificity makes the rendering process a lot simpler.
Summary
So to sum it up, nesting, whilst it may seem great keeping your code nice and readable, should only be used when absolutely necessary. It's very easy to forget what the CSS that is actually being produced looks like. Before you know it you'll be in nesting hell.
Languages like LESS or SASS give you more flexibility in declaring your style rules, and that can be good or bad depending on how you use it. The more flexibility you have in a language, the more you need design patterns and good practices to avoid making things worse than they were before.
LESS doesn't require that you always nest. You can always use CSS of course, and if you are applying a style to all p it might be better to define it globally, than to call mixins to obtain the same result on several nested ps.
But LESS and SASS do allow you avoid duplication, to write code that is clearer and easier to maintain, and other problems caused by the code duplication required by CSS.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am mostly a backend programmer, and am relatively new to CSS. So far, I hate it. My biggest complain is that is incredibly redundant and difficult to produce readable code.
Many times I need to apply styling to different but similar elements. However, I find it incredibly challenging to produce elegant code to do that.
The most simple way to do things in CSS seems to be to give an ID to everything and use custom code for every single element in the page, or classes when there are repeated elements with. However, this still leaves a lot of repeated code, like when I have two elements that are almost exactly alike, but have one or two different attributes, like width, background color, color or float side.
My current solution is defining many atomic classes, like
.bgRed { background-color: red; }
.bgBlue { background-color: blue; }
.fontCenter { text-align:center; }
.left { float: left; }
and so on, and applying multiple classes to an element, like this:
<span class='bgRed left' >My text</span>
But that's still very short of decent. Some attributes, like width and height, are usually strongly tied to it's elements, so I can't create an atomic class for it, and end up resorting to using it's ID.
Finally, my question: Why doesn't CSS support some kind function-like structure? Would a feature like this be useful in CSS? Is CSS badly designed or I just don't know how to use it properly? Why was CSS designed the way it is?
How I imagined functions in css would work:
Defining a css function:
_sidebar(float_side, color, width){
float: float_side;
backgroud-color: color;
width: width:
height: 200px;
color: #FE02A5
list-style: none;
display: table;
}
And applying:
<div cssfunc='sidebar(left, #FF0000, 150px)' >
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
Bonus question: How do you maintain you CSS code readable and organized, with minimal code repetition?
This is not the intended usage pattern for CSS. A general clue is if you have specific formatting words like colors or alignments in your class name, you're not following the "spirit" of CSS.
The intention for CSS classes is to use semantic categories for class names. For example instead of having a class named bgRed, use one called warning. The difference might be subtle in some cases, but the difference in philosophy usually helps maintenance. Instead of combining "literal" css rules at the element level, you'd combine more meaningful semantic ones like class="sidebar warning".
With that said, some people still find the lack of reusability of formatting between CSS rules cumbersome. There are fixes for that as well. The best solution is to use a CSS pre-processor like LESS or SASS. These languages compile into CSS, but support things like mixins and variables that function very much like the css enhancement you have in mind.
HTML defines what to show, CSS defines how to show it. If you use classes like "bgRed" or "left", you are doing this old way.
CSS doesn't define support functions, but LESS does. Imagine this:
.sidebar(#side, #color, #width) {
float: #side;
backgroud-color: #color;
width: #width:
height: 200px;
color: #FE02A5
list-style: none;
display: table;
}
.sidebar-important {
.sidebar(left, red, 100px);
}
.sidebar-misc {
.sidebar(right, blue, 50px);
color: grey; // overwrites .sidebar function
}
Then in HTML:
<div class="sidebar-important">Important news</div>
<div class="sidebar-misc">Something else</div>
This way, you can easily change values in LESS file, compile it to CSS and you won't need to change it in HTML.
Bonus answer:
LESS.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Let's say for example I am using some sort of frontend framework to design a website such as Foundation or Bootstrap.
I want to customize certain parts of the design in order to give it a unique feel, one that is different from the regular frontend look of it. What I have been doing is including the CSS for the framework then right after include another CSS, in which I write custom styles for the same classes that are used within the framework so they look like my unique look.
Is this the best way to go about customizing some sort of frontend framework like this, and if not, what would the cons be? Or is there a better way?
I realize one more request for a style page but other than that I can really only think that the browser might need to do a little more work when rendering the page. I do this so I don't have to go in and find every single element and class that I want changed within the framework's CSS.
I would never modify the original framework. Good practice is to include the modified classes in a separate style sheet as you have mentioned.
The advantages is you have never modified the original which could introduce bugs and to convert back to the default frameworks style will be as easy as removing your added styles.
If you can, I would modify the original css to your own design. This way your not making the user download one css file that just over rights the other css file. Also, I think it would make debugging easier as you only have to look in one file rather than two.
That is the best way also you could also add classes of your own and style them if you don't want to override the css framwork classes
I've been doing this with some elements in Bootstrap by adding !important tags in my main style.css file. There's no downside to doing this that I'm aware of.
.result-header .nav, .result-header .nav-bar {
position: absolute !important;
bottom: 4px !important;
margin: 0px !important;
}
.result-header .nav a, .result-header .nav-bar a {
padding: 1px 8px !important;
font-size: 14px !important;
border-radius: 4px !important;
}
Not every css element will need the !important, but it doesn't hurt to add it for each one. Just make sure you hierarchy your css (.result-header .nav-bar) if you only want to change the styling for a certain section.
If you're planning on changing the core foundation of the themes style (.nav-bar), you could edit the original file (making sure to backup anything you change), but I'd probably be best to create a whole separate stylesheet with only the theme changes and include it after the theme's original CSS:
.nav, .nav-bar {
position: absolute;
margin: 0px;
}
.nav a, .nav-bar a {
padding: 1px 8px;
border-radius: 4px;
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
One of the most challenging thing I have felt while working on (complex) web application is the organizing the CSS.Here are the different approaches we have tried on multiple projects.
1: Have a different stylesheet for every web page/module.
Obviously we were very new to web apps then, and this approach resulted in too many style sheets and too much repetition of styles. We had a tough time to achieve consistency across the application.
2: Have a common style sheets which is shared across the similar web pages.
This worked well for sometime until it became too complex. Also we found that we had too many exceptions which still resulted in tweaking common styles for particular cases, which if done incorrectly can affect different parts of the application and at some point it becomes difficult. Also having a large development team (across different time zones) and tough project timeline didn't helped our cause.
Although #2 works, but still we have seen our products still doesn't have the similar UI quality and consistency as we would like to.
Are there any CSS style guidelines that one should refer for very complex web 2.0 application. How do other people maintain their stylesheets?
I've found myself in similar situations.
First off, make sure that you're using CSS effectively. If you don't feel like you're an absolute pro at using CSS, take some time to study up and you'll significantly reduce redundancy and end up with a stylesheet that's easier to work with.
In most cases, there isn't much of a performance hit if you consolidate all of your styles into one file, and in fact, splitting your styles into dozens of files just so that you can be sure to exclude any that won't be used is likely to result in longer loading times because of all of the extra requests. But as I'm sure you know, a massive CSS file can quickly grow into a headache to maintain.
Consider this hack to achieve a compromise. Use your language of choice (PHP for me) to serve up your CSS. By that I mean include your style file like this:
<link rel="stylesheet" type="text/css" href="styles.php" />
, have the header of that file return it with the text/CSS content type, and have that file
a) Pull multiple stylesheets into one file
and/or
b) Change how the styles are written depending on various parameters (file being loaded, user data, time of day, etc.)
A is a good solution overall for reducing developmental headache and page-loading overhead. B will likely necessitate you also setting appropriate file expiration dates to avoid having the browser just ignore whatever new styles you want to generate at the moment in favor of what was downloaded on the last visit. Since you can usually accomplish the same thing in B as you can by simply having a static stylesheet and dynamically-written element class/ID names, it's generally not an ideal solution unless if you're doing something really strange.
And get a designer to advise you on this kind of stuff. Often it's hard for us developers to wrap our heads around some of the finer points of efficient CSS as well as people trained in that specific area.
I've been in this a lot of times. First, in the early times, I used to do just a stylesheet with everything inside, not much anyway, was the old times; then I decided for your second approach, the first one I luckily thought it was a mistake, too much code and pieces floating around...
The second approach is good up to the time when you start to make questions...
I mean:
Should the background style for this div go in the graphic.css or in the layout.css?
Should the font style go in fonts.css or in layout when comes to the width of the P?
Should the margin for a title with the icon position div go to the graphic.css or to the layout.css or to the fonts.css (it would be simpler to use the same declaration for the icon, the text and the position...)?
Then you realized there's something wrong about this approach.
What I do now is commenting. A LOT.
template.css -
/* ////// Headers ////// */
#header {
width: 1004px;
height: 243px; /* 263H-20MARG=243H */
padding: 20px 0px 0px 0px;
background-color: #000000;
background-image:url('../images/redset/top1-bk.png');
background-repeat:no-repeat;
background-position:right top;
clear: both;
}
/* logo */
#logo {
background-image:url('../images/redset/wh-logo.png');
background-repeat:no-repeat;
width:327px;
height: 263px;
float: left;
margin: -20px 0px 0px 0px;
}
#logo a {
width:327px;
height:263px;
}
/* Top menu & Banner */
#menuybanner {
text-align: center;
/* margin-right: 65px; optional*/
}
#bannerz {
height: 152px;
width: 653px;
text-align: left;
margin-right: 24px;
/* optional: width: 100%;
margin: 0px */
}
#bigmenu {
text-align: left;
margin: 18px 0px 14px 74px;
}
#bigmenu img {
margin: 0px 22px 0px 0px;
}
Originally this would have been in three different css: layout, graphics and texts. Now I know what everyone does.
By the way I know it rises the weight of the archive but I prefer not to do some mixed effects, cause everyone that comes after me and reads the css should be able to understand what I did and css like these:
a, .b, .c, .d, #f, #2 { background-color: black; }
Are really hard to unveil. Of course if you need to do it, go ahead, but I mean, sometimes they are just grouped like for nothing just to be more cryptic... like moodle... hahaha.
Hope being of help.
See ya.
You want to take advantage of cascading nature of CSS and the ways rules are inherited.
Code first the most general cases and then change specifics.
For a normal size project this should not get out of hand at all.
To see things more clearly you can use an index sheet and call other stylesheets from it. When you want to make changes you will know which stylesheet to go to and you will save time. Here is an example from one of my prqjects.
/*
This is the CSS index page. It contains no CSS code but calls the other sheets
*/
#import url("main/reset.css");
#import url("main/colors.css");
#import url("main/structure.css");
#import url("main/html-tags.css");
#import url("main/sign-up-sign-in.css");
#import url("main/pagination.css");
#import url("main/menu-items.css");
#import url("main/teachers-list.css");
#import url("main/footer.css");
#import url("main/misc-custom-sections.css");
#import url("main/error-messages.css");
Good luck finding your own style.
I use one mastersheet template.css which styles my main template. For any site which requires a seperate bit of styling that can't be covered by the main template I either put it in the site head, if it's short, or create a new sheet for that case.
Ideally I want to design the template.css file to be flexible to cover most cases.
I typically try to group my CSS by visual elements, and only include relevant stylesheets for a given page to keep my load times low. Using PHP or whatever environment you use to dynamically merge the required stylesheets into a single stylesheet for a given page is a good solution.
One thing that helps me is that I actually created pseudo namespaces for my CSS. I know that CSS 3 has support for namespaces, and that makes it easier, but since some browsers don't support it, this is what I do:
Create folders and files relevant to your project ( I use Java namespace style )
For example /css/com/mydomain/myprojectname/globalheader.css
Next, I use class names that map to the file system location
For example <div id='header' class='com-mydomain-myprojectname-globalheader-topClass'>
Use separators and good comments in your css file
For example /*---------------------------- begin link section --------------------*/
Use PHP or whatever to load these files and combine them into one stylesheet on load ( you could cache the resulting sheets if you are really clever. The namespace convention will prevent collisions between class names.
While the designers think this is verbose, it makes it really easy to find specific css classes in the file system, without a load time hit. Also, you won't have the problem of one designer / developer overwriting another's classes.
maintaining css files is a LOT easier if you can get everyone on board with utilizing cascading properly and keep your targeting strengths to the minimum.
Make sure that elements inherit styles and that overrides aren't too heavy will keep your css from getting crazy. By doing this, you then allow yourself to have just 2 or 3 style sheets for layout/base styles and overrides. If you put heavy control levels on what gets into the layout/base style sheets, and make regular trips in to reassess whats in the overrides sheet to see what can be moved up to the base and what can be simplified you'll free yourselves up to allow people to override at will, but also to keep control of creep.
There's my theory...