Alex Eguia's Codeblog

gem blurred_image_tag

1 Mar 2017

Sometimes it is mandatory to insert an image in a fixed width/height wrapper, either for aesthetic reasons, a fixed-dimension container, or other circumstances. The problem of creating elements with a fixed width and height is that the content needs to be processed to fit the measurements, possibly flattenning the images.

There are solutions both from the server side and from the client side to find out where the images “overflows”, and to be able to adapt the style in each case, but many of these solutions require a load time. A close-to-perfect solution can be one based on pure CSS as explained on the article Forcing image aspect ratio via CSS.

To keep the Rails’ DRY[1] motto, I have developed a Ruby on Rails gem defining a new method called blurred_image_tag that prints an image fitting it to its parent container’s width/height without being flattened. Its usage and params are the same as the native image_tag method.

Example of the blurred_image_tag gem usage with portrait and landscape images within a forced dimension div.

The main difference with the native method is that it creates a double <img> tag on the HTML: the first one to paint the blurred background, and the second one to print the image itself. This way, and using the CSS filter function, we can create fixed width/height image containers that neither flatten nor cut them by any side, with a blurred and semi-opaque background generated by the same image. Also, regarding the loading time, the same image is being referred twice, therefore the loading time will be the same as printing just one image since the cache of the web browser will reuse it.

To get the most out of this gem, or to collaborate with it, you can see the code and documentation in Github.

Rubygemsblurred_image_tag

Githubblurred_image_tag


[1] Don’t Repeat Yourself https://en.wikibooks.org/wiki/Ruby_on_Rails/Getting_Started/Don%C2%B4t_repeat_yourself

Forcing image aspect ratio via CSS

24 Feb 2017

Imagine we want to show a list of images:

1
2
3
4
5
<div class="image-container">
  <div><img src="http://dummyimage.com/200x200" /></div>
  <div><img src="http://dummyimage.com/200x200" /></div>
  <div><img src="http://dummyimage.com/200x200" /></div>
</div>

These will be well aligned if we use some CSS and flex:

1
2
3
4
5
6
7
8
9
.image-container {
  display: flex;
  flex-direction: row;
}

.image-container > div {
  margin: 0 10px;
  width: 100%; /* Flex takes care of this */
}

This code is acceptable for images that have the same aspect ratio, this is, the same ratio between its width and height (200x200px in the example above). If we change the images’ dimensions the result will be different:

1
2
3
4
5
<div class="image-container">
  <div><img src="http://dummyimage.com/300x200" /></div>
  <div><img src="http://dummyimage.com/200x300" /></div>
  <div><img src="http://dummyimage.com/300x400" /></div>
</div>

There are various solutions to this problem:

  • Resize every image by hand.
  • Implement a server-based image resizing algorythm (what about the processing time?).
  • Use just CSS and the padding-top technique as seen in sitepoint.com.
  • Use just CSS to force images to keep their aspect ratio (cleaner solution that the padding-top one IMO).

To keep the aspect ratio, we need images to have a <div> parent with position: relative, which is the one that will be in charge of having the necessary space so that the photo is embedded inside. A great use for this is in card elements, where the image container is preset with a fixed width/height or responsive measurements. Inside this <div> will be the image tag with position: absolute, being centered with the top, bottom, left, and right properties set to 0 and margin: auto, making the properties max-width and max-height the ones that define the width and height of the image. Basically we are forcing the image to “grow” from the center of its parent until one of the limits is reached (width, height, or both).

Let’s see it in action:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
.image-container {
  display: flex;
  flex-direction: row;
}

.image-container > div {
  margin: 0 10px;
  width: 100%;
  height: 180px; /* We have set a 180px height as an example */
  background: white; /* We have set a white background to see the image container width/height */
  position: relative;
}

.image-container > div > img {
  position: absolute;
  display: block;
  max-width: 100%;
  max-height: 100%;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}

We can see that the aspect ratio of the images are being kept, and they automatically place themselves in the optimum position without being wider or longer than their parent element, neither lengthen, flatten, or lose viewing areas, and remarking that it is a solution where the size of the main container doesn’t matter, so it can be used for any responsive view.

View the demo code on JSFiddle.

HSL color representation

5 May 2014

Most of us usually use the RGB color model. Its three components indicate, in hexadecimal from 00 to FF, the amount of Red, Green and Blue of a color; but this model can be tricky when it comes to change a color to be more bright, dark, or saturated.

Among the color models that can be used in graphic programs, or even in HTML/CSS, the HSL color representation is one of the most easy to play with. Its components are Hue, Saturation and Lightness:

  • H indicates the Hue, the color itself.
  • S indicates the saturation, i.e. gray, or a powerful color, like background: red, green, or blue.
  • L indicates the lightness, that is, from full black to full white.

This model is graphically represented as a cylinder, where the dimensions are set by the H, S and L values:

The values are ​​given by the following scale:

  • H: 0-360. See the color wheel to know what value matches your color.
  • S: 0-100. 0% is pure grayscale, while 100% is the full-saturated color.
  • L: 0-100. 0% is pure black, 50% the normal color scale as seen in the wheel, and 100% complete white.

With this color model, we can leave the S and L values fixed​​, to play with colors in the same tones. For example, to find a proper background color for a banner, we can desaturate the color a bit and give some lightness, to make it a range of pastel colors that can be adapted to any scenario. With this interactive tool you can change the color leaving the S and L values fixed at 33% and 66% respectively:

Thus, we can set up a template of a main page with a banner on top, with non-obtrusive colors. Here you can play with the HTML, CSS and JS of the template on jsfiddle.net.

Finally, another tool where you can play around with the HSL color model and create beautiful easy-to-change colors for your projects: http://hslpicker.com

Banner sample

Priority of CSS selectors

9 Abr 2014

We usually build our sites using third-party CSS (bootstrap, a CMS theme, etc.), and some selectors and properties might be overriden.

There are mainly three ways to define styles in our web, but the browser will give higher priority to the selectors and properties is this order:

1. External files set in withing the <head> tag
2. Properties in the <style> section
3. Inline properties within an HTML element with style=""
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- Type 1 -->
<head>
    <link rel="stylesheet" href="#" type="text/css" media="all">
</head>

<!-- Type 2 -->
<style>
    p {
        margin-bottom: 10px;
        color: red;
    }
</style>

<!-- Type 3 --> <!-- You'll burn in hell if you use this with no reason -->
<p style="margin-bottom: 10px; color: red;">

While using methods 1 and 2, CSS properties are set by selectors, being .class, #id, and tag the most used ones. In order to set properties to an element that is being referenced by multiple selectors, CSS is again based on priorities: the highest rank the selector gets on a given formula, will be the one defining CSS properties, and the losing selectors’ properties will be overriden. The formula is calculed as follows:

a = Inline style (type 3)
b = Number of ids (#) on the selector
c = Number of classes (.) and pseudo-classes[1] on the selector
d = Number of HTML tags on the selector
Formula: 1000*a + 100*b + 10*c + d

The selector with the highest rank wins[2], in case of tie prevails the one which is defined later in the CSS file. Operators like >‘ and ‘~‘ either add or sustract points in the formula:

1
2
ul li { ... }     /* Rank: 2 */
ul > li { ... }   /* Rank: 2. Latest declaration -> Wins */

We can also use the !important declaration, which gives the highest priority to that property, but it’s said to be not clean enough, hence it’s recommended to declare with classes and ids as many HTML elements as we need.

Some examples to make this clear:

1
2
3
4
5
6
ul li { ... }                             /* Rank: 2 (1 + 1) */
.red { ... }                              /* Rank: 10 */
#myID { ... }                             /* Rank: 100 */
#myID .red { ... }                        /* Rank: 110 (100 + 10) */
#myID .red div > ul { ... }               /* Rank: 112 (100 + 10 + 1 + 1) */
#myID .red div li:first-child { ... }     /* Rank: 114 (100 + 10 + 1 + 1 + 2) */

[1] Pseudo-classes: [class*=”red”][type=”button”], [id=content]. The last one, even referring an id, counts as a pseudo-class selector.
[2] It’s not really a 10-base sum, as a selector with 11 HTML tags has less priority than one class selector, but you do have a problem if you use a selector that huge 🙂

Moving WordPress URL

8 Feb 2014

WordPress is one of the most used CMS, but there is some configuration data hardcoded in the database we should be aware of when we’re moving our site to another URL. Normally the main URL is coded on some configuration file like config.php, and every link is relative to that string, but this doesn’t happen on WordPress.

Assuming we are not moving our files nor database[1], but only changing our URL, we should start by defining the basics:

1
2
Old site: http://old_page.com
New site: http://new_page.net

First of all, edit your web server configuration

1
nano /etc/apache2/sites-available/example

and add a ServerAlias with the new website URL. Once the whole migration process is done and tested, we should consider removing the original ServerName in case the old link won’t be used anymore:

1
2
ServerName  old_page.com
ServerAlias new_page.net

Reload your web server:

1
/etc/init.d/apache2 reload

Your new URL must be working, but WordPress’s links will still point to the old site, which are hardcoded into the database. Now it’s time to switch to our database manager to execute these lines:

1
2
3
# Change MYWPDATABASE with your actual db name
UPDATE MYWPDATABASE.wp_options SET option_value = REPLACE(option_value,'old_page.com','new_page.net') WHERE option_id>0;
UPDATE MYWPDATABASE.wp_posts SET guid = REPLACE(guid,'old_page.com','new_page.net') WHERE ID>0;

Now every link has been changed with the desired URL, unless you hardcoded them in your posts or pages. Didn’t you? Maybe your client did 😉

1
UPDATE MYWPDATABASE.wp_posts SET post_content = REPLACE(post_content,'old_page.com','new_page.net') WHERE ID>0;

This would change every hardcoded link inside your posts’ content.

We should be done, but maybe there are some third-party plugins which also hardcode the URL in their settings. In this case, you should check for new tables created by these plugins in your database, and search for the old URL.

It’s also recommended to search for some configuration file containing the old URL inside your WordPress files:

1
grep -r "old_page.com" /var/www/example

[1] In case you are moving your WP files and/or database to another server, you should first dump your WordPress database, import it into your new server, then copy your WordPress folder, change the config.php file if you have changed any database configuration, and configure your web server. Also remember to check your permissions in case you didn’t do a secure copy with the scp command.