Archive

Posts Tagged ‘CSS’

Safari clear/float text flow issue

July 3rd, 2013

safari-bug
Here’s a strange and annoying Safari quirk I’ve stumbled upon yesterday, applies to both the Mac and Win versions. Basically, if there’s a text and two right floated elements (read images), and the first element is longer than the paragraph it precedes, and the next paragraph is also preceded by such a floated element, the result will be the text overlapping the floated element – see attached image. Here the code to replicate it: http://jsfiddle.net/TmJ9q/

If anyone knows any workarounds, just drop a comment. Others have reported this here, here and here, with the following test cases: http://jsfiddle.net/JwXke/28, http://jsfiddle.net/VaBCd/

 

CSS ,

Updated version of the Magento CSS & JS Minifier

May 31st, 2012

I’ve released the first version of the magento css&js minifier more than a year and half ago. Since then, it has been downloaded over 200 times – roughly 10 downloads per month. It’s a decent number, considering its utility and the fact that it hasn’t been promoted or included on Magento Connect. The first version was compatible with all Magento versions greater than 1.4. Starting with Magento 1.7, the extension failed to work on the admin pages, because of the -webkit-keyframes css declarations.

What’s new in version 1.0.1

  • Changed namespace from Oxygen to Mandagreen
  • Upgraded JsMin to version 1.1.2
  • Upgraded CssMin to version 3.0.1
  • Added backend options for converting HSL values, converting font-weight values, converting named colors and replacing variables

 

Download & Install

Minifier for Magento (1396 downloads) , then unzip it and copy the app/ folder to your Magento root folder.

Logout from the admin if you’re already logged in, then log back in. Go to Cache Management, click on the “Flush cache storage” button, then go to Configuration > Developer and Enable javascript minifier and css minifier under CSS & JS Minifier. Also, make sure that “Merge JavaScript Files” and “Merge CSS Files” are enabled, under JavaScript Settings, and CSS Settings respectively. Go back to Cache Management and click the “Flush Javascript/CSS cache” button.

 

Upgrading from 0.1.0

If you’re already using the first version of the extension, you’ll need to remove the old files. Go to your magento root folder, then navigate to the etc/modules folder. Remove the file called Oxygen_Minifier.xml. Then, navigate to app/code/local and remove the Oxygen folder (or Oxygen/Minifier, if you have other modules with this namespace).

Next, issue the following mysql command, using the mysql console or PhpMyAdmin:

update core_config_data set path = replace(path, 'oxy_', 'mg') where path like '%oxy_minifier%';

You can now install the module as explained above.

 

Compatibility

This extension has been tested with all Magento CE versions 1.4 through 1.7.

 

Supporting the Module

If you enjoy using the Magento CSS & JS Minifier, help us improve it and make it even better. Since this project it entirely open source and free for everyone, we welcome any donations and consider them a sign of appreciation. Donate

We also appreciate your feedback, both positive and negative, as long as they are constructive.

If any of you know how to package an extension for Magento Connect, I would appreciate the help. I’ve given up after 2 hours or repeated failures.

Magento , , ,

Introducing Magento CSS & JS Minifier

September 15th, 2010

As the title says, I’m glad to announce my first public Magento extension (not yet added in the Connect repository). During my 3 years experience with Magento, I’ve worked on a lot of custom extensions, improvements & fixes, but most of them were client-specific, plus they weren’t designed to have a backend interface (with a few exceptions). This one, however, is entirely configurable from the Admin and it’s both simple and effective.

 

What it does

This quick optimizer parses all javascript & css files included on a page and removes all unnecessary characters. The most simple step is to remove spaces, tabs and new lines – but there’s more than just that. Of course, for small files compression is insignificant, but when you work with almost 600KB and around 30 requests, you can save a lot. Here’s a quick math on one of my Magento installs:

Javascript – 26 requests, 479 KB
CSS – 4 requests, 102 KB

With Magento’s default merging enabled:
Javascript – 1 request, 360 KB (not sure why this is smaller then the 26 summed up, but nvm)
CSS – 1 request, 108.2 KB (same for this one too, but again, nvm)

We’ve already saved 28 requests, which means less overhead – quicker download times for user, less stress on the server.

With the Minifier enabled:
Javascript is 255 KB, which means almost 47% compression
CSS is 92 KB, which means almost 10% compression

 

Advantages

 

Disatvantages

  • Need to write javascripts very careful, adding a semicolon after almost everything
  • Have to rewrite of Mage_Core_Model file
  • Have to override two Magento methods
  • Additional processing time (insignificant in my opinion)

 

Credits

This plugin wouldn’t exist if it weren’t for these two outstanding PHP projects:
Joe Scylla’s CssMin
Ryan Grove’s JsMin
Big thanks to both of them.

 

Download & Install


First, Minifier for Magento (1396 downloads) , then unzip it and copy the app/ folder to your Magento root folder.

Logout from the admin if you’re already logged in, then login. Go to Cache Management, click on the “Flush cache storage” button, then go to Configuration > Developer and enable all the options, as shown in the attached screenshot. Go back to Cache Management and this time click on the “Flush Javascript/CSS cache”.

Go to your store frontend and behold, you’re now using compressed js’s and css’s.

Works on Magento 1.4+

Updated on May 31st, 2012 – all download links in this page refer to the latest version of the plugin. Some explanations on this post might be inaccurate. For the latest details please check new post called Updated version of the Magento CSS & JS Minifier

Magento , , ,

Fixing PNG CSS backgrounds on IE6

December 17th, 2009

ie6-png-problems
Today I was stuck (again) on a really annoying IE6 glitch. In the photo, screenshot #1 is the correct display in IE6 after the fix (and all other “sane” browsers before the fix), while screenshot #2 shows the glitch. Basically, IE6 decided to replicate the beginning of the same image on all items.

You might think the problem was in my HTML code, or maybe in my CSS code. The HTML is 100% valid and following all modern guidelines: only a’s, li’s, div’s and text nodes. So, the problem could be in the CSS file – which applied a single sprite sheet on all the li’s, div’s and a’s, through background-position. In case you’re wondering what css sprites are, have a quick look: http://www.google.com/search?q=css+sprites&hl=en

So, after adding zoom, z-index, removing position: relative;, removing overriding classes, changing all background declarations to background-image, background-repeat, background-position declarations, the problem persisted. In other words, none of the regular methods worked.

After a quick-search on the internet, I found some articles discussing PNG overlaps and transparency on IE6, but also mentioning background-position‘s (http://www.dillerdesign.com/experiment/DD_belatedPNG/, http://www.hotscripts.com/forums/css/45733-solved-css-newb-overlap-issue-ie6-2-links-issue.html). Just then I realized that the problem might be with the file format – stupid, in my opinion, but not in IE6’s opinion.

Changing the file from a regular 8-bit PNG to a GIF solved the entire overlapping problem. No CSS intervention (other than changing the reference to a .gif file), no HTML edits, just an image format change.

 

Conclusion

If you don’t need images with an alpha channel and want to use background-position‘s with those images, and want to make it work with IE6, stick to GIF files. If you don’t care about IE6, then this will definitely not be not a problem for you.

 

CSS , , ,

Reducing the number of CSS requests

September 11th, 2009

One common problem with larger/trafficked websites is that they end up serving a considerable amount of css data. Most of the frontend developers use individual style sheets for resets, structure, design, homepage / innerpages and so on. In fact, there’s no other rule here than keeping the css code as maintainable as possible. This also means adding comments and maybe writing every declaration on a single line, using indents.

Another well-known problem is with caching. When the CSS file is changed, most of the times you’ll need to clear the browser cache in order to display the site correctly, with the new changes applied. Well, for users that’s not an option and all the css upgrades should be reflected instantly. I know what you’re saying: there’s Apache’s mod_expire for that, but there are times when you cannot use that or don’t know about it or you don’t know how to get it running. If you fall into this category, this article should solve that.

Let’s take an example first. On the homepage of a site, there are 3 style sheet files requests. Their total size is 46,274 bytes – that’s roughly 46KB. My aim is to only request a single CSS file and make it change its name when anything in those 3 files changes. The site uses templates, so this tutorial will be based on that architecture – for plain ole’ php-html sites, this should be even simpler.

So let’s write a list of what needs to be done:

  1. Reflect any css change into the file name so browser’s cache is instantly invalidated
  2. Combine all requested files into a single file
  3. Create a queue of css files: both templates and controller files should be able to read & write to the queue.


Step 1 – Changes to the Template Model

In the template model, add new public methods for addCss( $cssFile, $media = 'screen') and getCompiledCss($media = 'screen'). Here’s how it could look like:

function addCssFile( $file, $media = 'screen' ) { 
	$this->cssFiles[] = array( 'url' => $file, 'media' => $media ); 
	return $this; 
}

function getCompiledCss( $media = 'screen' ) {
	if( $this->compiledCss instanceof CompiledCss ) { return $this->compiledCss->getFilename(); }
	if( !count($this->cssFiles) ) { return null; }

	$cssMedia = array();
	foreach( $this->cssFiles as $css ) {
		if( !isset($cssMedia[ $css['media'] ]) ) {
			$cssMedia[ $css['media'] ] = array();
		}
		$cssMedia[ $css['media'] ][] = $css['url']; 
	}
	if( !$media || !isset($cssMedia[$media]) || !count($cssMedia[$media]) ) { return null; }
	
	$this->compiledCss = new CompiledCss( $cssMedia[$media] );
	return $this->compiledCss->getFilename();
}

Maybe the getCompiledCss seems complicated, but in fact it’s not. It’s just a proxy method with some lazy-initialization in it. It only checks to see if the CompiledCss object is instantiated (creates it if it’s not), then return the compiled CSS file name. So basically, everything is done in the CompiledCss class.


Step 2 – Changes to the template

All valid and W3C-compliant CSS declarations go in the header of the HTML, so it should be easy to group all CSS requests together and call the getCompiledCss somewhere in the main layout file or in a head template component. Either way, here’s a quick peek at how the templates could look like:

<?php 
	$this->addCssFile('general.css', 'screen')
		->addCssFile('homepage.css', 'screen')
		->addCssFile('panels.css', 'screen');
?>
<?php if( $this->getCompiledCss('screen') ): ?>
	<link type="text/css" rel="stylesheet" href="<?php echo $this->getCompiledCss('screen'); ?>" media="Screen" />
<?php endif; ?>


Step 3 – CompiledCss Class – main logic

As we’ve seen above, 99% of the logic is done inside this class, so tasks #1 & #2 are its responsibilities. First of all, remember that inside the Template Model there was only a call for getFilename() – let’s take a look at it:

function getFilename() {
	if( null === $this->filename ) {
		$this->compile();
	}
	return $this->filename;
}

Again, it’s pretty simple – all it does is to call the compile() method once. Otherwise, if this method is called more than once, it just returns the same file name. As you can see, complie() does the entire job, actually, so on with it:

First, make sure each css file gets compiled only once, then sort their names alphabetically, so that the generated file name is always the same, no matter the order you add the files (I know this can cause some serious issues – but bear with me until the end for problems, solutions & improvements

$this->cssFiles = array_unique($this->cssFiles);
asort($this->cssFiles);

The file name will need to parts: one for recognizing the css files that are “inside” and another one for content checksum – the second part helps generating new file names when the source files are modified.

$filename = $out = '';
foreach( $this->cssFiles as $css ) {
	$filename .= Crc32($css); 
	$cssPath = 'path/to/css/files/' . $css; #whatever path you need to get to the css files
	if( is_file($cssPath) && is_readable($cssPath) ) {
		$out .= file_get_contents($cssPath);
	}
}
$filename = Crc32($filename);
$checksum = Crc32($out);

We need to cache this compiled css, to be able to serve CSS data. As opposed to the method of requesting a list of css files on a GET request, this one needs to save the parsed css someplace, otherwise decoding the checksums would be almost impossible. So, write the “processed” css data to a file and than load it each time it is requested published here. Here’s the code for actually compressing the css:

$output = preg_replace('#[ \t]+#', ' ', $output); #replace multi-spaces or multi-tabs with a single space
$output = preg_replace('#[\n\r]+#', '', $output); #remove new lines
$output = preg_replace('#([:;])\s+#', '$1', $output); #remove spaces after : and ;
$output = preg_replace('#/\*(.*?)\*/#', '', $output); #remove all comments
return $output;


Step 4 – Final touches

One more step is required for this to work. You need a php file handling the compiled css request. Let’s assume your requests (and compiled file name) look like this: crc32-crc32.css. That means you’re gonna create a mod_rewrite rule in a .htaccess file mapping 8 chars, dash, 8 chars, dot css to a php file, passing both checksums as parameters. Inside the php file, just send some headers and request the file:

header('Content-Type: text/css');
header('Cache-Control: cache');
header('Pragma: cache');
header('Expires: ' . gmdate('r', strtotime('+1 year')));
echo CompiledCss::request( $firstChecksum, $secondChecksum );  

request() logic is quite simple – check for existing cache and display it, otherwise just return null. Usually, if the process runs normally, first we’re gonna get the getFilename() call which saves the cache and returns a valid file name, and just after that the request() method fires.


Compression performance

Like I said in the beginning of this post, the original file size for all three requests for this example was roughly 46K. After compilation it got to 42K – that’s around 91% of the original size, aprox. 10% compression.
Best compression level with this tools was 13%, but the usual rate is 10%. Keep in mind, however, that it depends on how the css file is written. For example, I write each declaration inline, so there are only a few spaces and new lines, but for indented css the compression could reach 20% (tested).

So there you have it. At least 10% improvement, a few extra requests saved, and the ability to invalidate browser cache on-demand. I’ve been using this tool for a while now and I can tell you I have no design/layout problems or conflicts and the total size of css requests have saved enough bandwidth – not to mention that download times are reduced. Add mod_deflate or manual gzip compression to it and it’s gonna download even faster.


Problems, Solutions & Improvements

I know some of you might have seen only problems in this article. Or you might thing this is way too complicated and it’s not needed cause there are other ways (much more simpler and faster) of doing it. So let’s see what problems I’ve identified so far and what you can do:

Problem: if CSS files are sorted and they are not compiled in the same order as they’re given, there might be conflicts, overlapping styles, and in the end the design might be screwed up.
» Solution(s): One of them is to improve your css declarations making them work the same, no matter how they’re parsed. The other solution is to remove the sorting in the compile() method, but be sure to always use the same queue push to get the same filename. For example, pushing a.css, b.css in one place an b.css, a.css in another place will create two separate css cache files.

Problem: crc32 only uses 32 bits, so checksum collisions might occur (although the chances are minimal)
» Solution: Switch to md5 or even sha1 if you think those don’t create collisions.

Problem: when stripping spaces after :;, there are chances to affect strings, like for instance url’s.
» Solution: try to keep your filenames free of : and ;, or, if this isn’t enough, remove this line: $output = preg_replace('#([:;])\s+#', '$1', $output);
The same applies for removing multi-spaces and multi-tabs.

Problem: removing comments might break some IE hacks
» Solution: hacks are not recommended anyway, so try using separate IE6- and IE7+ stylesheets, if nothing else works. Again, removing that line from the output parsing helps, but eventually the compression level would be zero.

Improvement: gzip the css and server gzip content if the client accepts gzip. Try enabling mod_deflate anyway, if load is not really an issue.

Improvement: check you inodes cache settings to help speeding disk reads – as you’ve noticed we’re reading all css files each time a page is requested, so some system tunin might help.

PHP , ,

Create a gallery with fade-in effects using Mootools

March 21st, 2009

I was working on a photo gallery a couple of days ago and I thought I’d write a tutorial on adding neat effects on a gallery of items (usually photos).

Demo | Mootools Gallery (835 downloads)

The problem

I was showing 12 photos on a page and I didn’t like how it loaded – it simply looked too static. So I though of adding a nice fade in effect to each item. This could be even more useful when loading the photos via an AJAX request, which I intend to add to that gallery at a later time. First, let’s take a look at the gallery HTML:

<ul class="gallery">
	<li class="clear">
		<a href="#"><img alt="img_01" src="img/01.jpg"/></a>
		<h2>Image #1</h2>
	</li>
	<li>
		<a href="#"><img alt="img_02" src="img/02.jpg"/></a>
		<h2>Image #2</h2>
	</li>

	...

	<li>
		<a href="#"><img alt="img_12" src="img/12.jpg"/></a>
		<h2>Image #12</h2>
	</li>
</ul>

I’m gonna add some basic CSS on this list, just to make it look like a grid, rather than a list – of course you can apply any styling on it.

.gallery {width: 540px; margin: 0 auto;}
.gallery li {opacity: 0; filter: alpha(opacity = 0); float: left; width: 100px; padding: 5px 10px 15px;}
.gallery li.clear {clear: left;}
.gallery li img {border: 1px solid #ccc; width: 100px;}

You can’t tell from the missing li elements, but I’m clearing each 4th element to create a 4×3 grid. Ok – so far the grid is in place, but we need the animation part – we could use any javascrpit framework, but for this project I had to use Mootools – for those of you that haven’t seen it and don’t what it is about, here’s a quick overview from their site: MooTools is a compact, modular, Object-Oriented JavaScript framework designed for the intermediate to advanced JavaScript developer.

The solution

First, we need to fetch all li elements:

var li = $$('ul.gallery li');

then apply the animation effect:

li.each(function(e) {
e.set('tween', {duration: 500, transition: 'back:in'}).tween('opacity', 0, 1);
});

A few comments on this last piece of code:

  • e.sets(…) – set the duration to 500 and transition to “backIn” to all tweens
  • e.tween(‘opacity’, 0, 1) – animate (or tween) opacity from 0 to 1, using the options defined above

If you run this code you can clearly see that it doesn’t exactly produce the desired effect – all photos fade-in at once, because of the way the code is executed. The trick is to add an incremented timeout to each element:

var i = 0; //the current timeout
li.each(function(e) {
  i += 100; //adding the increment
  setTimeout( function() {
    e.set('tween', {duration: 500, transition: 'back:in'}).tween('opacity', 0, 1);
  }, i);
});

And that’s all! We now have a nice item-by-item fade-in effect. It’s worth mentioning that this effect can be changed by tweaking the three variables: the delay for each item, the speed of the effect and the tween effect. On the demo page I’ve made it possible to change the delay & speed, so you can make an idea of how they affect the general effect. The third parameter can be changed using any mootools transition (http://mootools.net/docs/Fx/Fx.Transitions).

Demo | Mootools Gallery (835 downloads)

Javascript , ,