Related
I ran into a problem at working with Shopware today. I want to restrict the usage of certain CSS files (mobile css and desktop css).
Problem is: both files are being used and it seems to not letting me restrict the files to the viewports. What did I do wrong?
Would be great if you could help me out here, since Ive just started in LESS templating. Cheers!
{extends file='parent:frontend/index/header.tpl'}
#phoneLandscapeViewportWidth: 30em;
#tabletViewportWidth: 48em;
#tabletLandscapeViewportWidth: 64em;
#desktopViewportWidth: 78.75em;
when (#media screen and (min-width: #tabletLandscapeViewportWidth)=true) {
{block name="frontend_index_header_css_screen" append}
<link type="text/css" media="screen, projection" rel="stylesheet" href="{link file='frontend/_public/src/css/custom.css'}" />
{/block}
}
#media screen and (max-width: #tabletLandscapeViewportWidth) {
{block name="frontend_index_header_css_screen" append}
<link type="text/css" media="screen, projection" rel="stylesheet" href="{link file='frontend/_public/src/css/mobile.css'}" />
{/block}
}
First of all: As the comments already state out, you're mixing up different languages.
By now - from your example - you're dealing with three things, that cannot be combined in that way as you try it:
LESS: This is a preprocessor language that - at least in a Shopware 5 context is meant to be compiled and generates your CSS
files (there is a way of including LESS files directly, but this is not recommended for production, so I'd leave this part out).
CSS: Your stylesheets that are rendered. If you statically include them into your template (I mean if you're not using Javascript to dynamically change your DOM) you WILL have to decide whether you use one or another CSS-File before you render the DOM.
This brings us to the next CSS related-topic:
Media Queries: The concept of media queries is not meant to dynamically change the DOM (i.e. clearing out one CSS-Stylesheet and bringing in another).
Imagine the following case: You sit at your Desktop-PC and slowly drag the window of your browser smaller and smaller until your viewport-width is smaller than 64em (#tabletLandscapeViewportWidth). What is the media-query supposed to do? Request the server to load another resource?
Remember: Media Queries are CSS and CSS is all about style of your Website. In a normal case it is served once when the page loads and the rest of the magic happens in your client. There is no further communication with the server (and this is what you'd try to do, i guess).
Smarty (.tpl): The third part you mix up here is the .tpl files, and these come from the Smarty-Template-Engine. So we have to be clear here: Smarty renders your template. This happens server-side before the page is delivered to the requesting client.
That means you can decide to load one or the other css at this point (but not by media-queries, I'll come back to that later) but once the page is delivered to the client, Smarty's work is over and it will do nothing without another server-request (i.e. by an AJAX-call).
I must confess that I am not absolutely understanding what exactly you want to achieve. If you only some CSS definitions to a certian viewport width, you don't need to go into the template at all.
Let's assume you only want your styles that are in the custom.css apply when the viewport is larger than #tabletViewportWidth and everything below should serve mobile.css.
Since you can nest media-queries in CSS3 it shouldn't be a problem to wrap the whole less file into a media-query like that:
#media screen and (min-width: #tabletLandscapeViewportWidth) {
// all your custom.css content
}
#media screen and (max-width: #tabletLandscapeViewportWidth) {
// all your mobile.css content
}
But please keep in mind that this excludes all other media-types, so you maybe should go with #media all.
If you really want to change the stylesheets dynamically you should go with a library like Modernizr and make an AJAX-Request that dynamically changes the stylesheet, but imho this is kind of an ugly solution that only makes (no real, but with a bit of fantasy a little bit) sense if no stylesheet is loaded (or a base-stylesheet with styles, that both .css-files share) and the call is made to request a smaller CSS-File.
But if the production-css-file is minified this shouldn't be worth the effort.
As you can see, in the offered solution we are not even touching a smarty-tpl-file. But i want to mention a little thing if you work with smarty:
You're extending a file here, therefore every junk of code needs to be inside of the {block}-tags you're extending. Smarty doesn't know where to put the code otherwise and will throw an error (even though, as explained LESS-Code won't work anyways here ;) ).
regards
I know placing all your styles in a CSS file is the best thing to do as it is a lot neater.
But does it REALLY matter if the styles are inline or in a CSS?????
Edit below
My plan is to just place the styles in my MasterPage and all other pages will use the MasterPage....I believe the correct term is not "INLINE" but Embedded???
Some thoughts from one with experience, rather than a 'purist':
Storing all styles, for a large application, in one CSS file is not maintainable. You'll have perform a text search of the file to find the style you're looking for, or scroll a lot, and there's a higher chance that you'll overlook related styles when making an update.
If certain styles are particular to a page, not globally used, it is more maintainable to keep them in a style tag within the head tag.
Deep CSS inheritance hierarchies are also not maintainable. These are much, much worse than inline styles!
The CSS language itself does a poor job of applying styles to many elements in more complex structures. Consider lesscss, sass, or even jQuery for more than basic application of styles.
Lots of developers use HTML for presentation, mostly DIVs, when they think they are doing the right thing, or lecturing others. Some example above!
Using Inline CSS:
Repeat the same rule for every
element in the page.
More code and bigger file size to
transfer to the client.
Harder to maintain, suppose you want
to change the width to 200px, you
will need to go through all the page
and edit one by one.
inline:
<div style="width:100px; height:100px;"></div>
<div style="width:100px; height:100px;"></div>
external OR put css classes in the head [embedded styling]:
<div class="big"></div>
<div class="big"></div>
Based on your edit: that seems not to be inline CSS as in my example above, it is the same idea as using an external file, so if you want to do that go ahead, it is the same.
It matters because your code becomes very difficult to maintain or update if you use inline styles. Keeping your styles in style tags or separate CSS files allows you to comply with Don't Repeat Yourself, which is probably the most important development principle.
That being said, if you are absolutely certain that a piece of styling is unique to a given element, and also that it won't ever need to be tweaked, you can feel free to use inline styling. I sometimes use inline style for throwaway code and for things like landing pages (once they're done, they're done).
No but it is alot easier to make changes to the css if you only have to look one place instead of all your headers/inline
One other thing, your markup looks alot cleaner if you dont have eny css/javascript inline
When creating master pages I use in-line styles to create the basic layout of the page. For instance I include all of the styles that position the header at the top of the page, main content in the middle and footer at the bottom. Pretty much every style attribute related to positioning, I include in the masterpage as an inline style.
Storing styles in one document helps you to control on your entire project. Furthermore less code to maintain and applying changes.
It is a loth easier for maintenance... does it really matter depends on what you think what is important... why wouldn't you use a css file?
Do you mean putting your styles in the with or attaching them as 'style="x"' to your element?
There's several reasons for avoinding inline CSS.
1) Maintenance, it's easier to make changes to a code where all css is seperated from the markup itself. It also makes the code more readable as avoiding alot of inline css gives you less code.
<div class='test'></div>
is easier on the eye than:
<div style='background:yellow;width:10000px;height:10px;position:absolute;top:10003px;left:132032px;'></div>
When the css is inline you will also have a hard time finding where the code itself is and comparing styles. You will also often end up repeating the same code several times because you can't use classes.
2) Performance, CSS files can be gzipped, making for a smaller load. It's also easier for the browser to handle when it get js and css served as files.
3) Keeping with the best practice. Some other poor developer might want to edit your code later, and he sure would be happy if you kept away from inline CSS.
Now of course you can do CSS in the head of a document too, but why make your files bigger than they need to be? More code into the same file makes for more mess. And you can't gzip it if you do.
#Etienne , there is one disadvantage doing this way , if you want to deploy any changes to production you have make a build and push it.
If you maintain everything as css , you can just push the css file changes and invalidate the load balancer cache.
I thought this is a good point to mention.
When it is best to use inline style
Inline style is the best solution in situations when some style is created dynamically from user input via server-side code (ex, WordPress plugin), to be applied only to a single HTML element, in such cases insert it into an external CSS file causes only problems:
There is the need for a server-side code that creates a CSS class
with the dynamic style inside it.
There is the need for a server-side
code that write and save the .css file
There is the need for a
server-side code that is able to link the CSS classes created to the
correct HTML elements You must load an external CSS file for no
reason, this is a downgrade of performance (file size and 1 more HTTP
request)
In many cases, where the dynamic codes are just one or two,
the problems are startling clears: you must create a file of ex.
800bytes with 2 lines of code, and load it as external files.
Greater exposure to bugs. More a code is complex more are chances of bugs. The server-side codes above are very complex in comparison to the simplicity of the task they do.
Real use-case:
Imagine a scenario where a user wants to upload an image and use it as a background in an HTML element. With old rule is just style="background-image:URL()". with the new rule some code must create and save an external file, with just the code style="background-image:URL()", create a CSS class for it, write it in the HTML component, load this CSS file with just one line of code. Totally nonsense. Consider also that this operation must be done every time the user updates the image.
Final result:
Worst performance due to 1 more HTTP request and large, complex, server-side codes.
Wasting hours of time for authors to develop something that is not only useless but also creates real problems.
At least one more file in the project
Worst readability/comprehensibility of the code because a user must check the HTML and then find the CSS code of the linked CSS class to see the value of the style.
When it is best to use an external CSS file
In all other cases than the ones explained above, in short, when the style is fixed and never change you should put it in an external CSS file.
I'm setting up an image cluster for a webpage (similar to sprite-map) for performance reasons. I have a utility that generates the master image, and css to reference the image map.
For simplicity sake, I'd rather include the new css after the regular css file, instead of writing a script to search and replace all the classes in the original css. Something like so in the html (psuedo code):
<LINK href="normal.css" rel="stylesheet" type="text/css">
if(%=usingImageCluster=%)
<LINK href="master.css" rel="stylesheet" type="text/css">
So all the styles that are defined in normal.css would get overridden by the new styles in master.css.
Couple of questions:
Besides the "duplication" of information, does this override cause performance issues?
Will the browser still pull the non-clustered images, because the original CSS file is still included (negating the positive performance gains of image clustering)?
Is there a guarantee that the last loaded style will always be the one applied?
Besides the "duplication" of information, does this override cause performance issues?
Yes, you are generating a new HTTP request for the second external stylesheet. Too many HTTP requests is the #1 slowdown factor for most webpages.
Will the browser still pull the non-clustered images, because the original CSS file is still included (negating the positive performance gains of image clustering)?
Yes, the browser will pull ALL images from the first and second CSS file. Performance time will increase almost linearly (approximate). Especially if you are rewriting every css selector, or changing lots of images.
Is there a guarantee that the last loaded style will always be the one applied?
Yes. Unless the first sheet uses !important on certain style attributes, the last declared styles for a selector will always be applied. This is where Cascading Style Sheets get their name.
I'm just wondering what others do in this respect:
Do you try to keep positional CSS (layout) separate from color/flavor CSS (color, background-color, background-images, font-size and family) ?
Use two stylesheets? Combine two stylesheets server-side? Abstraction layer for the CSS?
or you don't even try?
I know sometimes after working on the same web project for six months I can usually live with the positional CSS but end up wanting to change the colors/images.
I tend to keep all the CSS together, without separating "color styles" from "positional styles" or "layout styles". I find that when I often try to debug a specific "module" it's easier to have all the CSS rules applied to one selector, and not spread out over the style sheet.
However, I do suggest you read Creating Sexy Stylesheets over at thinkvitamin.com. One thing I do is list the rules in a certain order everytime, so I know within the declaration block where to find what I want.
More info at Jina Bolton's http://creatingsexystylesheets.com/
You'll find that in large-scale projects, layout and color/flavor CSS will (if you're smart about it) usually just happen to be separate. Firstly, if you're catching yourself setting color/font-size/font-family style rules over and over, you're wasting your time. Typically you should define your fonts in one place: the body tag. Any additional fonts should be defined in their respective tags... h1, h2, p, etc. In my opinion it's not good practice to give these tags positional directives; they should be placed inside a div that will be responsible for their layout. Same goes for color and font size. I think the only exception to the rule would typically be background stuff, which is especially true if you have lots of gradients and fancy things like that.
Really what it comes down to is planning; a well-planned project needs very few color/flavor style rules. So to answer your question, yes, I usually have a "Global.css" file that defines all of my fonts and colors for h1-h5, a, p, and any other tags that will contain text.
Edit:
Usually, since the projects I work in are fairly large-scale and have a number of different modules, we separate the styles with in a sort of hierarchy; this makes sense because of the way CSS works -- as long as you don't change the style-rules put into place at the "base" (or in our case, the global.css) somewhere down the line, the styles will stick. This helps because when we want to modify the font of our site, we simply change the font-family rule at the "body" tag, and it will propagate throughout the entire site.
So, our stylesheet layout works something like this:
Global.css (Fonts/Text/Primary font colors)
--> genericBase.css (basic page structures such as columns that are used throughout the site)
--> nav.css (left-hand nav and/or top nav bar)
--> formLayout.css (labels, inputs, fieldsets, any other form stuff)
-----> forums.css (individual modules' styles that may deviate a bit from the usual structures, or simply things specific to those pages)
-----> blogs.css
-----> messages.css (etc etc etc)
The arrows here are meant to imply the "order" of the files in the hierarchy. The longer the arrow, the further down in the style-sheet the rules these files contain would be, if we had put all of the styles into one file.
So you see, the whole idea is to start with very general styles and work your way down to the most specific. Remember that the order in which your CSS files load matters to the browser. You can use this to your advantage. The interesting thing is, by the time we get to our specific modules' css files, we have very few styles to write because most of the other important stuff has actually work itself out along the way.
So like I said, planning is vitally important. I've found that this methodology makes it easier to "debug" my styles, and I use almost no hacks at all, usually only for silly ie6 stuff.
Let me know if you need more information. I'm glad this is helpful to you.
I used to separate them but it was more difficult to maintain. The problem is that many "formatting" properties will have an effect on the layout and many "layout" properties may actually be design.
Some examples:
While "border" may be considered a "formatting" property, they do take some amount of space so you will need to adjust your layout when setting or removing borders.
"line-height" is tied to the font-size and may be considered a "formatting" property, but it has a huge influence on the size of your elements and how they vertically align each other.
Margins and paddings are sometimes needed for the layout and sometimes used just for formatting.
If you think hard about it, there are very few properties that actually are purely formatting or purely layout.
It's often easier to just keep everything in the same file and try to keep it clean by having your declarations orders, related properties grouped, etc.
I keep everything together in a single file and use the folders feature in CSSEdit to keep it organised. Web design company Viget have a blog post about this technique here.
I separated my layout and color styles recently, and I now have several css files, which i import as follows:
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<link rel="stylesheet" type="text/css" href="style-default.css" title="Default Style" media="screen" />
<link rel="alternate stylesheet" type="text/css" href="style-bw.css" title="Black and White" media="screen" />
All layout is in style.css, then colors are in style-default.css.
This way I have a standard style, but users also have the option to change the colors. This not only offers options for the user, but it makes it easy to make color changes without touching the layout (I tend to change my colors much more often).
In Firefox my color options show up in the view menu under "Page Style."
I've fallen into the pattern of separating my CSS out into the following:
Layout (headers, footers, logos - general chrome)
Typography (fonts, sizes, re-usable inline font styles)
Widgets
The latter category is generally made up of CSS code I re-use between projects, and usually gets split down itself into:
Forms (left-aligned, right-aligned, styles for required fields, etc)
Grids (2-col, 4-col, etc etc etc - about 20 or so varieties)
Hacks (IE/other CSS hacks)
Other stuff (AJAX widgets, toolbars, comment boxes, etc - anything re-usable)
For colours, I just keep a cheat-sheet text file around. Keeping them in a separate stylesheet will probably only work if you are very, very disciplined.
I have started to use classes to handle colors specifically.
.element{margin, padding, layout stuff}
.ourcolor{#some color}
It lengthens the class attribute though:
< div class="element ourcolor" >
However, I can reuse the color:
< span class="ourcolor" >Some text
So far I prefer it as adjusting colors is much easier.
As Mark W pointed out, Creating Sexy Stylesheets is a fantastic read. One thing they do advocate is separating the styling concerns through a framework:
screen.css - A screen CSS file can either have all your styles you want to be used for on screen, and/or can import additional styles, such as the following:
reset.css - A reset CSS file can be used to “reset” all the default browser styling, which can help make it easier to achieve cross-browser compatibility.
typography.css - A typography CSS file can define your typefaces, sizes, leading, kerning, and possibly even color.
grid.css - A grid CSS file can have your layout structure (and act as the wireframe of your site, by defining the basic header, footer, and column set up).
print.css - A print CSS file would include your styles you want to be used when the page is printed.
If you follow this pattern, the colors would go in your typography.css, and layout would be in your grid.css.
I keep everything in one file and only provide different files for alternative styles (e.g. for printing).
Within that file I keep the overall layout (columns, headeer & footer) seperate from the actual contents (paragraphs, headings, lists...)
I am used to thinking object oriented, so I group the styles for different objects (menus, blog posts) together. From that perspective, colour and position both belong to the same object and therefore are kept together.
I am wishing for the ability to define colours once in a style sheet, assign them a declarative name (e.g. 'HeadingColour') and then use the name when assigning the colour to a selector...
I'm building a new site for my company, and I'm at the stage where I've created the html mockup of the first page. I'm going to use this as a basis for the rest of the site. I'm thinking of organising my stylesheet better now I've got the design looking consistent cross-browser, but I'm wondering how far to go when I'm breaking it up.
One idea is to have the following:
reset.css
typography.css
layout.css
colors.css
but where do I draw the line? theoretically I could go on and break them down into classes, ids etc, but I think thats going overboard.
Does this seem a reasonable method?
Coincidentally, A List Apart had an article covering this today. They recommend separating out into a few main categories, including some you listed (type, layout, color), but going further to include various tricks to keep older browsers happy.
On the other hand, keeping everything in one css file keeps the requests between browser & server down. A compromise might be to keep things separate for development, and merging for production (as a part of your build process, naturally :p).
I don't tend to split typography into a seperate stylesheet, although it seems like a good idea. I'd keep colours with typography though. My typical way is to have the following structure:
base.css
Global style used throughout the site
Aims to be extendable, for example so that it can be reskinned (but using the exisiting layout) for a microsite.
Implements/imports reset.css
page.css
Implements any page-specific changes.
microsite_skin.css
See base.css point 2
Pickledegg,
There's nothing wrong with breaking up style sheets. In fact, I find it very useful to organize css rules into different files based on their type, or what parts of the site they are applied to. If you lump rules into one large file, it can quickly become a mess and become very difficult to manage.
I would recommend coming up with your own scheme for separating your rules into files, and stick with it for all your projects.
I would break layout down into 2+ more parts, Base layout, IE Hacks, Menus (one for each menu area. This could be something like a top menu and a side menu)
If the site where to change color depending on the area I'd add one for each color area as well.
You also could use Yaml or similar as a base framework for your layout.
I'd keep the different stylesheets seperate while designing only merging them into 2-4 depending on the site shortly before uploading/releasing. always keeping the Hacks apart.
Separate them based on what you estimate your needs are going to be later on. If you think the typography, layout, or colours (globally) are going to change, then it's probably wise to at least delineate styles in that way so it's easier to replace one stylesheet with another later on.
But if you go too far in this you'll end up with duplicate rules everywhere (eg. #content having a font-family rule in typography.css, a color rule in colors.css, etc). That's not a logical way to split things up unless you anticipate the key changes to be taking place there.
If, on the other hand, like most sites the graphic design is going to remain fairly static but the architecture is going to have some changes made (eg a new content type) then you want to be grouping your styles based on the context of the site. For instance, article.css, search.css, etc.
Essentially, try to look ahead at what changes are going to be needed later on and then try to anticipate those changes in your css file setup.
The major problem IMO, is the duplicate property definition issue. This makes style-sheets unmanageable. To bypass this issue the divide and conquer approach is used. If we can ensure manageable style sheets with non-conflicting rules, then merging sheets or modularising them would be easy.
During reviews all I do is check for rule conflicts, classitis and divitis. Using Firebug/CSSTidy combination, the problem areas are highlighted. Thinking in these lines, I don't even look into typography and font-separation.
The goal is to have a singel base CSS file and separate browser hacks files. Multiple base CSS files would be needed if an application has different themes.
I put all styles, including IE6-and-7-specific styles, in one sheet. The IE6 and 7 styles are targeted using conditionally-commented divs that only appear if one of those browsers come to the site, e.g.:
<body>
<!--[if IE 7]><div class="IE IE7"><![endif]-->
<!--[if IE 6]><div class="IE IE6"><![endif]-->
... rest of markup ...
<!--[if IE]></div><![endif]-->
</body>
Not sure what people think of this approach, but the extra markup is negligible, and being able to include IE6/7 styles next to main styles without the use of hacks... just prepending the selector with ".IE" or ".IE6" etc, is a big convenience.
As for multiple stylesheets... save your HTTP requests. Use image sprites, one stylesheet, one "application.js" javascript, etc.
I'd still include separate sheets for the print and handheld styles, but that's about it...
Don't go too much further than that. If you do have to, try and find a way to merge them before production. The biggest issue is that you begin stacking up HTTP requests. It's not so much an issue for the browser but the amount of requests that need to be made for each page. I would say you are at a good point, more than 4 would be going somewhat overboard. Remember you can always use good commenting and formatting to break up large CSS files.
Whenever I'm trying to decide how far to break apart some files (I usually do this with code modules, but I apply the same principals to my css/js) I break it down to the smallest reusable files that make sense together. This isn't the best for the flow of data across the wire, but it makes maintainability of my source a lot easier. Especially if you're going to be having a lot of css floating around.
If you feel comfortable taking your colors.css and using the whole thing in another location without modification then you're probably fine.
Take a look at blueprint-css. Blueprint is a CSS framework which supplies a variety of default styles to you (such as browser reset code).
The style sheets in blueprint-css are organized as follows:
screen.css - default styles for screens
print.css - default styles for printing
ie.css - Internet Explorer specific fixes
application.css - contains the styles you write. Actually you shouldn't modify the previous three style sheets at all, because these are generated by blueprint-css. You can overwrite all blueprint-css styles in your application.css file.
For further details refer to the blueprint-css Git repository.
I break mine up almost exactly the same way:
reset.ccs - The standard reset from MeyerWeb
typography.css - Fonts, sizes, line-heights, etc
layout.css - All positioning, floats, alignments, etc.
colors.css (or more appropriately skin.css) - All colors, background images, etc.
These are then followed with IE-specific files included via conditional comments for the appropriate version.
I haven't had the need to separate them further, though I do organize each file in separate sections (base elements, named elements, classes, etc.)
UPDATE: I have changed my system a bit in the last few projects I have done.
base.css - Contains the CSS from the YUI reset and YUI base CSS files (with attribution)
main.css - Contains #import statements for the following:
typography.css - Fonts, sizes, line-heights, etc
layout.css - All positioning, floats, alignments, etc.
theme.css - All colors, background images, etc.
print.css - Overrides for the other CSS files to make the pages print-friendly.
I also then use conditional comments to add any IE-specific CSS files if needed.
My next step in improving this would be to add a build-process step to combine all of the CSS files into one file to reduce the HTTP requests on the server.
Everybody recommends to break. I'll be the devil's advocate.
How about NOT breaking style sheets. At least for production purposes is better to have a single request instead of many. The browser can process 2 simultaneous HTTP requests. This means that other 2 requests can be made after the first 2 are completed.
Combined files are a way to reduce the number of HTTP requests by combining all scripts into a single script, and similarly combining all CSS into a single stylesheet. Combining files is more challenging when the scripts and stylesheets vary from page to page, but making this part of your release process improves response times.
Yahoo and Google recommend this.
Google is recommending creating 2 files. One for everything necessary at the startup and 1 for everything else.
I think that even designers have to think in optimizing terms, not only hardcore developers.