Archive for CSS

Over the past couple of years, CSS has gotten a set of new properties that allow us to create quite advanced graphical effects right in the browsers, using a few lines of code, and without having to resort to graphics editors to achieve those effects. If you are like me, then that sounds like music to your ears. I don’t do well in graphics editors and would choose a code path over a graphical editor path any day. CSS now allows us to do more graphical work right in our text editors.

Examples of graphical effects that we can create using CSS today include textured text effects, photo effects like color editing/tweaking, photo and element blending that also enable us to blend elements with other elements, clipping content to arbitrary shapes, and more. You can even wrap content to arbitrary shapes with CSS too!

CSS has gone a long way, and in this article I want to give you an overview of the CSS features that allow us to create such graphical effects—namely blend modes and filter effects.

Color Blending with CSS Blend Modes

If you’re a designer who frequently fires up a graphics editor such as Photoshop or Illustrator, then you’ve inevitably come across blending modes at some point or the other during your work, since blending is one of the most frequently used effects in graphic and print design. Blending operations, also known as blend modes provide us with a fine level of color blending control that enables us to perform operations such as inverting colours, mixing them, highlighting them, and more.

Different blend modes, when used, yield different effects. And a blend mode is used to specify how an element, known as the “source” will blend with its backdrop—also known as the “destination”.

In CSS, the element’s backdrop is the content behind the element and is what the element is composited with. Compositing is the fancy term for the process of combining an graphic element with its backdrop.

When you blend two elements in CSS with each other, only the areas where these elements overlap will be affected by the blend mode you choose because, as you can imagine, only those areas are where these two elements can be blended.

Before the CSS Compositing and Blending specification was introduced, CSS already offered us one way of compositing elements known as simple alpha compositing. This is what the opacity property is for. By changing an element’s opacity, the browser makes it translucent so that the colours of its backdrop can show through.

Today, two main properties exist in the CSS compositing and blending specification that enable us to blend elements with other elements and an element’s background images by specifying one of 16 available blend modes. These two properties are: background-blend-mode and mix-blend-mode.

Blending Background Images Using The background-blend-mode Property

The background-blend-mode property, as its name suggests, is used to specify a blend mode for an element’s background layer. A background layer can be an image, or the background color.

The background-blend-mode property is used to specify the blend mode for each background layer.

If the element has more than one background image, you can specify multiple blend modes—each blend mode will be used for a background image such that the first blend mode in the list corresponds to the first background image in the list of background images, and so on.

For example:

background-image: url(first-image.png), url(second-image.png);
background-color: orange;
background-blend-mode: screen, multiply;

The second-image.png background will blend with the background color using the multiply mode, and then the first-image.png background will blend with the second image and the background color using the screen blend mode. (Reminder: the first background image in the list is the one on top, and the ones following it are beneath it.)

The background images will only blend with each other—they will not blend with any content that lies underneath the element itself.

There are 16 blend modes available in CSS: normal (which is the default blend mode and means that no blending is applied), multiply, screen, overlay, darken, lighten, color-dodge, color-burn, hard-light, soft-light, difference, exclusion, hue, saturation, color and luminosity. (For the sake of brevity, I will refrain from going into technical detail about each of these modes, and will recommend this article instead to learn all about them.)

These blend modes will modify the colours of a background image resulting in a different effect for each mode.

The hardest part comes when picking a blend mode to achieve a specific effect is knowing which mode to pick. It is very hard—if not impossible—to predict the result of applying a certain blend mode to an image.

The following image shows a set of results achieved when applying the above mentioned blend modes to an image. The image is being blended with a red background color. The order of blending operations from the top left corner of the image is the same as the order mentioned in the list above.

background-blend-mode-examples

The result of applying the different blend modes to an image, in the same order mentioned above, starting from the top left corner.

Usually, the way to choose a blend mode is by trial and error. Apply the blend modes to your image and settle for the one that achieves the effect you’re after.

Some blend modes, however, yield expected results and you can memorise those and use them whenever you need. For example, the luminosity mode allows you to create monotone images (bottom right corner)—this is a handy tip to keep in mind for when you’re after creating that big header image with a white heading on top which became very trendy during the past year.

As part of an article I wrote a while back, I created an interactive demo which allows you to upload your own image and preview the different blend modes on it. You can play with the demo here.

Screenshot of the interactive blend modes demo.

Screenshot of the interactive blend modes demo.

Blending background images is great and you can achieve some really neat effects using this property. The following image shows an example of blending an element’s background image with a linear gradient image also used as a second background image on the element. This image is taken from this live demo from the Codrops CSS Reference.

The result of blending a linear gradient background image with a photo background image on an element.

The result of blending a linear gradient background image with a photo background image on an element.

More creative effects can be created when you get to blend an element with other elements on the page. This is useful for when the images you’re blending need to be foreground images—not background images, and when you want to blend a piece of text, for example, with the image behind it. This is where the mix-blend-mode property comes in.

Blending Elements with Their Backdrop using mix-blend-mode

Probably one of the most useful and practical use cases for mixing elements is mixing a piece of text with some image behind it. And this is where the interesting effects come in. Think fixed headers blending with the content as the page scrolls down, or text blended with an image in the background, or text blending with other text, etc. Using the mix-blend-mode property you can do exactly that.

Just like background-blend-mode, the property accepts one of the 16 blend mode values available. Again, to see this in action, you can refer to the interactive demo mentioned earlier.

The following screen recording shows how you can add a piece of text and then blend it with an image of your choice using one of the different blend modes.

mix-demo

Screenshot of the interactive demo showing the mix-blend-mode property in action.

An example blending a piece of text with a background image behind it could look like the following. Assuming the piece of text is contained in a wrapper that has a background image applied to it, we could have something like:

<div class=“wrapper”>
    <h1>This is a blended heading</h1>
</div>
.wrapper {
     background-image: url(path/to/image.jpg);
   background-size: cover;
    /* … */
}
h1 {
    mix-blend-mode: multiply;
     /* other styles here */
}

You can also blend text with other text, allowing you to achieve nice colourful text overlapping effects like the one shown in the top right corner of the following image. All of the effects shown in this image can be achieved using different CSS blend modes.

blending-examples

Examples of effects created using CSS blend modes.

Using negative margins or relative positioning, you can shift the position of one word so that it overlaps with the word next to it, and then apply a mix-blend-mode to the word to blend it with the other word. The possibilities are endless.

Blending Notes

Sometimes, you may not want to blend an image or an element with its backdrop, or you only want to blend a group of elements together but prevent these elements from blending with other content behind them. This is where stacking contexts come in play and, using a property called isolation, you can isolate a group of elements so that they only blend with each other and don’t blend with other content on the page.

By creating a stacking context on an element, you can isolate the content of that element and prevent them from blending with the backdrop of that element. However, you can still apply a blend mode to the entire context to blend it with its backdrop.

Moreover, If you are using the background-blend-mode property, the isolation property is not needed since background layers must not blend with the content that is behind the element, instead they must act as if they are rendered into an isolated group (the element itself), as specified in the specification. This is why the isolation property will have an effect when used with the mix-blend-mode property, but not with the background-blend-mode property.

You can learn more about the isolation property here.

Note that the mix-blend-mode property also allows you to mix or blend SVG elements too.

Browser Support

CSS blend modes support is getting better by the day. You can keep an eye on browser compatibility for the background-blend-mode property here; support for mix-blend-mode can be found here.

Whether or not a property has full browser support, you can always start using it as part of a progressively enhancing workflow. These blend modes can be used to enhance your page designs, while falling back to non-blended alternatives in non-supporting browsers. By using a feature today, you’ll help push it forward and your design will eventually look right in other browsers as they support these features. So don’t let a limited browser support stop you from having fun with these properties today!

Image Adjustments with CSS Filter Effects

A filter effect is a graphical operation that is applied to an image as it is drawn into the document. It can be described as an operation that passes an image through a filter and then renders the output of that image on the screen.

One way to think of them is like a filter placed on the front of a camera lens. What you’re seeing through the lens is the outside world modified by the effect of the filter. What you see on the screen is the content modified by the filters applied to it.

To apply a filter to an image using CSS, you use the filter property defined in the CSS Filter Effects specification.

Filter effects include, for example, blur effects, drop shadows, and colour shifting and manipulation like saturating/desaturating colours, among others.

There are ten primitive filter effects in CSS, and a filter is applied to an element by passing a filter function to the filter property.

The ten filter functions are:

▪ blur()
▪ brightness()
▪ contrast()
▪ grayscale()
▪ hue-rotate()
▪ invert()
▪ opacity()
▪ saturate()
▪ sepia()
▪ drop-shadow()
▪ url()

Each of these functions is used to manipulate the image’s pixels and colours, and each function takes a parameter value that specifies the degree or intensity of the filter applied.

Conceptually, any parts of the element are effected by filter operations. This includes any content, background, borders, text decoration, outline and visible scrolling mechanism of the element to which the filter is applied, and those of its descendants.

The blur() function

The blur() function is used to blur an element by applying a Gaussian Blur to that element. It takes a length value as a parameter; this value needs to be a positive number and cannot be set in percentages. The larger the value the more blurred the element will be. A value of zero will leave the element unchanged.

What’s interesting is that since the parameter of the blur() function is a length value, this means that you can use any possible length unit, like em and rem.

The following are examples of valid blur() values:

blur(.5em);
blur(7px);
blur(0);
filter: blur(); /* equivalent to blur(0); */

The following image shows the result of applying a 10px blur to an image:

blur

The brightness() function

The brightness() function is used to manipulate the image brightness. It is used to make the image look more or less bright. It adjusts an image’s colours between completely black (zero brightness) and the original image colours (100% brightness). A value of zero will render the image completely black. A value more than 100% will increase the image brightness.

You can also specify the amount of brightness using a number instead of a percentage such that a percentage value of 65%, for example, would be expressed as 0.65 instead.

For example, the following are all valid brightness() values:

brightness(150%);
brightness(0);
brightness(0.7);
brightness(0.01);
brightness(200%);
brightness(10%);

The following image shows the result of applying a 200% brightness to an image:

brightness

The result of applying a 200% brightness to an image.

The contrast() function

The contrast() function adjusts the contrast of the image. That is, it adjusts the difference between the darkest and lightest parts of the image.

The function is similar to the brightness() function in that, just like brightness(), a value of zero will render an image completely black. As the value increases towards 100%, the difference in darkness changes until you see the original image at 100%. Values beyond 100% will increase the difference between light and dark areas even more. If no value is passed to the contrast() function, it defaults to 100% and the image is not changed.

contrast() also takes the same values as brightness(), so the following are all valid examples:

contrast(150%);
contrast(0);
contrast(0.7);
contrast(0.01);
contrast(200%);
contrast(10%);

And the following image shows the result of applying a 200% contrast to an image:

contrast

The result of applying a 200% contrast to an image. (That is one angry cat there! ;))

The grayscale() function

The grayscale() function converts the image into a shade of grey.

The value is also a percentage or a decimal number equivalent to that percentage. However, the percentage values need be between 0 and 100%. Any value greater than 100% will be clamped to 100%. 0% leaves the image unchanged while 100% makes it completely grey. The higher you go from zero to 100% the more the image loses its colours and becomes grey.

The following are all examples of valid greyscale() values:

filter: grayscale(); /* defaults to grayscale(100%) */
filter: grayscale(1); /* same as grayscale(100%) */
filter: grayscale(36%);
filter: grayscale(0.28);

The following image shows the result of applying a 100% grayscale to an image:

grayscale

The result of applying a 100% grayscale to an image.

The hue-rotate() function

The hue-rotate() filter function rotates the colours of an image by an angle that is to be passed to the function as a parameter.

A simpler way to understand this would be to imagine a color wheel. Every color on the color wheel has an angle at which it is positioned. If you start at one point (color) at the circle and then move along the circle by a certain angle, you end up at another point with another color.

What the hue-rotate() function does is it selects each color of the input image, rotates it by the angle value passed to it, and then outputs the image with the input colors replaced with new colors. All the colors in the image are shifted in the same way to produce new colors.

A value of zero renders the image unchanged. The maximum angle of rotation is 360 degrees. If the value for the angle is not provided, it defaults to the value 0deg and the image is not changed.

The following image shows the result of applying a 120deg hue rotation to an image:

hue-rotate

The result of applying a 120deg hue rotation to an image.

The invert() function

The invert() function inverts the colours of an image. It takes a value between 0 and 100% such that the higher you go from zero to 100% the more the image will look inverted. A value of 100% is completely inverted—all the colours are flipped so that the image looks like a photo negative (like the ones generated for old non-digital cameras). Any value over 100% will be clamped back to 100%. A value of 0% leaves the input unchanged.

Note that if you don’t pass a value to the invert() function, it defaults to 100% and the image is completely inverted. And the percentage values can also be represented as decimal numbers as well.

The following are examples of valid invert() values:

invert(); /* equivalent to invert(100%) */
invert(0.24);
invert(60%);

The following image shows the result of inverting an image’s colours completely using a 100% default value:

invert

The result of inverting an image’s colours completely using a 100% default value.

The opacity() function

The opacity() function is similar in functionality to the CSS opacity property. It accepts values between 0 and 1 or its equivalent 100%. 100% means the image or element is fully opaque, and as you go down from 100% to zero, the element becomes more and more translucent until it becomes completely transparent at zero, and then the content on the page that lies behind it—if any—will show through it. Even if you pass in a value greater than 1, the browser will clamp it down to 1/100%. Negative values are not allowed.

The following image shows the result of applying a 0.5 opacity value to an image:

opacity

The result of applying a 120deg hue rotation to an image.

The saturate() function

The saturate() function saturates the colours of the image making it look more vivid. It takes a value between zero and 100% or the value’s equivalent decimal number. A value of 100% leaves the image’s colours unchanged. The value of zero completely desaturates the image while a higher value saturates the image more, and values greater than 100% will super-saturate the image. Negative values are also not allowed.

Saturating images is particularly useful for when the image’s colours are looking dull and you want to give them a more lively appearance.

The following example shows the result of applying a 250% saturation value to an image:

saturation

The result of applying a 250% saturation value to an image.

The sepia() function

Ever heard of “the sepia effect”? You likely have—ißßt’s that effect that gives a vintage appearance to an image. The sepia() function gets its name from the fact that it adjusts an image by giving it a sepia tinge like in old photographs.

Just like previous functions, it takes a value (percentage or decimal) between 0 and 100%. The higher you go from zero the stronger the sepia effect. Values greater than 100% will be clamped to 100%.

The following is the result of applying a 100% sepia tone to an image:

sepia

The result of applying a 100% sepia tone to an image.

The drop-shadow() function

The box-shadow CSS property allows us to apply a box shadow to an element. This means that even if you have a non-rectangular element or a non-rectangular image (like a PNG), the shadow applied to that element is going to be rectangular as if the element is a rectangular box. This, in many scenarios, is an unwanted results.

For example, suppose you have the following PNG image of a star. Since it’s a PNG, it is made up of some fully transparent areas, and the star is the only opaque area. When you want to apply a drop shadow to the image, you’ll likely want to achieve the following result:

drop-shadow

An image with a drop shadow applied.

Using box-shadow, you’d end up with something like this instead:

box-shadow

An image with a box shadow applied.

This looks ugly.

The drop-shadow() filter function allows us to achieve the previous result.

The drop-shadow() function takes a value similar to the value accepted by the box-shadow property, except that the drop-shadow() function’s shadow does not include a spread radius like the box-shadow‘s does, and the inset keyword is also not allowed in the drop-shadow() function. I’ll assume you’re familiar with the values of the box-shadow property. If not, please refer to this entry in the Codrops CSS Reference for a list of possible values and detailed explanation and examples of each.

To apply a drop shadow using drop-shadow(), you pass in the value of the shadow you want and simply apply it to your image. For example:

.png-img {
    filter: drop-shadow(10px 10px 3px rgba(0,0,0,0.3));
}

The url() function

The url() function allows you to use a filter defined in an SVG document and apply it to your element. Instead of using one of the above 10 filters, you can define your own filter in SVG and then apply it to the element by referencing the filter’s ID in the url() function. For example:

/* filter from an external SVG file */
filter: url(myFilters.xml#effect);
/* or filter defined in the main page */
url(#myFilter);

The following is an example of a blur filter defined in SVG:

<svg height="0" xmlns="http://www.w3.org/2000/svg">
  <filter id="myFilter" x="-5%" y="-5%" width="110%" height="110%">
    <feGaussianBlur in="SourceGraphic" stdDeviation="8"/>
  </filter>
</svg>

Referencing that filter in CSS and applying it to an element would apply a Gaussian blur filter to that element.

Since SVG filters are a big and wide topic, we won’t be getting into the details of them in this article.

Live Demo!

Because CSS Filters are not supported in all browsers, I showed screenshots of the effects in all of the previous examples. That being said, you can still play with the filter values in the following live demo:

See the Pen 7405c808441c8021bb6bc59baef72441 by Sara Soueidan (@SaraSoueidan) on CodePen.

Just like with CSS blend modes, you can use CSS filters to enhance your pages, so you don’t need to wait for full browser support to start playing with and taking advantage of this cool CSS feature.  

Multiple filters

You can apply multiple filters to an image or element. When you apply multiple filters to an element, the order in which you apply those filters matters and changes the final output of that element. If you apply multiple filters, these filters should be space-separated. For example:

filter: sepia(1) brightness(150%) contrast(0.5);

 

Animating filters

Filters can also be animated, this allows you to create some really creative effects. An example of multiple filters being animated on an image is the following image fading effect by Lucas Bebber:  

See the Pen Pretty Fade by Lucas Bebber (@lbebber) on CodePen.

Lucas’s work is extraordinary, so you might want to check his Codepen profile out for more beautiful experiments that are sure to spark your creativity.. and curiosity.

Order Of Graphical Operations

In addition to blending and filters, an element could also be clipped and/or masked. If you apply more than one graphical operation to an element, the browser needs to decide which operation to apply first, and depending on the order, the end result would be different.

There is one specified order of operations in CSS according to the specification: first any filter effect is applied, then any clipping, masking, blending and compositing.

Inspiration

Not long ago, Dudley Storey created a neat experiment using CSS blend modes and clipping paths to create a 3D Glasses effect.

3d-glasses

Screenshot of Dudley’s 3D Glasses demo using CSS blend modes.

You can check his demo and tutorial out here.

Final Words

CSS Blend Modes and Filters are only two of the features that CSS proves us with to create graphical effects on the web. Other effects also exist that bridge the gap between print design and web design, giving us—web developers and designers—more control and better tools for designing in the browser, without having to resort to graphics editors to achieve such simple—yet powerful and impressive—effects.

If you’d like to learn more about other CSS graphics features, make sure to leave a comment below requesting a followup article.

I hope you found this article useful. Thank you for reading!

Comments (0)

Creating an image carousel (slideshow) using HTML, CSS and Javascript is a challenging task that only advanced web designers and developers can accomplish, right? Wrong! In this Your Questions Answered post, we’ll be walking you through how to build a responsive carousel in Dreamweaver CC using the Bootstrap Carousel Plugin from w3school.com.

Unless you have been living under a rock for the past couple years, you’ve probably heard of the term responsive web design and you likely know what it is. However, in case you’re not sure it’s a technique for building websites that dynamically adapt to any screen or device based on the size, resolution and orientation.

Bootstrap is a HTML, CSS and JS framework for developing responsive, mobile first projects on the web.

Building a Responsive HTML Carousel Using Bootstrap

To get started:

  1. Launch Dreamweaver CC.
  2. Select Site > New Site.
  3. In the dialog box that appears, enter the following information:
    1. Site Name
    2. Local Site Folder: Click the Browse or Folder icon. Navigate to any of your local folders you want to use for this project.
    3. Click Save
  4. Create an image folder under the Site you just created and call it “img”.
  5. Copy your images to this folder.
  6. Select File > New.
  7. Select Blank Page, page type as HTML, and Layout as none.
  8. Save the page as slideshow.html.
  9. Open this page in your web browser.
  10. Copy the contents below Edit This Code.
  11. In Dreamweaver, select the content in Code view and paste the content that you copied.
  12. In the HTML section of the code, edit the <img> tag to read <img src=”img/<nameofimage.jpg>”> For instance, for the first image, I used <img src=”img/img_chania.jpg”>
  13. I have edited the H3 Tag and the P tags to add the relevant captions for the images. You could do that as well.
  14. Select File > Preview in Browser to preview in a browser of your choice.

Resize the browser window. The images and captions in the slideshow should resize to fit the new dimensions of the screen.

Tell me more

If you look in the <head> section of your code, you should see the following:

<meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

What is happening here is that the page is linked to CSS and JS files at remote locations. Dreamweaver gets the contents of these files and displays them for you. Because the files are at a remote location, you cannot edit them in Dreamweaver.

Feel free to click on each of the files to look at the code contained in each of them.

For a list of websites and applications built using Bootstrap, see http://bit.ly/1F1QArx.

Comments (0)

Applying background images to elements is probably one of the most used features in CSS, and many background properties exist that allow us to control different aspects of an element’s background.

An element can have more than one background image. If you want to apply more than one background image, you can provide them as a comma-separated list of values for the background-image property. The background-position property is used to specify the position of the background image, and this property is worth a deeper look because its different possible values have different results, some of which might be new to you if you are not very deep into CSS.

To keep the code and concepts throughout this article simple, we’ll be positioning one background image throughout the examples. But what applies to one background image applies to multiple images as well.


A background image is positioned inside what is called a background positioning area of an element. This background positioning area,as the name suggests, specifies the area inside which the background will be positioned, and has a coordinate system used to handle the positioning.

Before we dig into the concepts of positioning further, let’s first have a quick look at the CSS box model and see how it affects the positioning of background images inside an element.

The CSS Box Model Areas

An element in CSS has three areas, called boxes, defined on it: the border box, the padding box, and the content box. The border box is the area of the element that includes its entire innards plus the area underneath its border.

The padding box is the area of the element that excludes the border and includes the element’s content and the surrounding padding — specified using the padding property.

The content box is the area created by the element’s content, excluding any padding and border.

box-areas

An element’s box areas. Image Credit: The Codrops CSS Reference, background-origin entry.

There’s also a fourth area called the margin box which includes the element and its outer margin that you specify using the margin property.

When you give an element a background—be it an image or a solid color—that background is painted across the element’s padding area by default. (This behaviour can be modified using the background-origin property, but we’ll get to this shortly.)

In order to specify where exactly the background image will go inside the positioning area, this area needs a coordinate system used to translate the position values into. Let’s take a closer look at this coordinate system before we move forward.

An Element’s Coordinate System

By default, and due to the nature of an element’s box model in CSS, every element has a coordinate system established by its height and width. This coordinate system is used to position the element relative to other elements, and to position the element’s descendants relative to the element itself.

An HTML element has a coordinate system in CSS. SVG elements, on the other hand, don’t have a similar coordinate system because they are not governed by the concept of the box model.

The origin of the coordinate system in CSS is located at the top left corner of the element.

A background positioning area is also governed by a coordinate system established on that area, and is used to position the background image in that area. This coordinate system also has its origin at the top left corner of the positioning area.

Since the default positioning area is the padding box, then, by default, the origin of the background positioning area’s coordinate system is the top left corner of the padding box.

This means that when you apply a background image to an element, the browser will position the first and subsequent repetitions of the image starting from the top left corner of the padding area.

For example, suppose you have a background image applied to an element and you do not set that background image to repeat (so only one instance of that image is applied). The initial position of the background image inside the coordinate system is at the origin of the padding box’s coordinate system. So, the top left corner of the image is positioned at the top left corner of the padding box. (See live example below.)

See the Pen Adobe background-position by Sara Soueidan (@SaraSoueidan) on CodePen.

Using the background-position property we’ll talk about in this article, we can then change the position of the image inside that coordinate system.

But as we mentioned before, we can change the background positioning area and this, in turn, will change the origin used to position the image inside the element’s background area.

 

Changing The Background Positioning Area & Coordinate System Using background-origin

The background-origin property is used to change the origin of the coordinate system used to position the background image in the background positioning area.

It takes one of three values: padding-box (which is the default value, content-box and border-box.

Depending on the background positioning area you choose, the corresponding background origin — the origin of the coordinate system established on that area — will change, and so will the initial and default position of the background image.

The following live example shows the different background origin / positioning areas in action.

See the Pen Adobe background-origin — different values by Sara Soueidan (@SaraSoueidan) on CodePen.

For each background positioning area specified using background-origin, the coordinate system will “shift” to cover that area.

Then, we can specify the position of the background image in that coordinate system using the background-position property.

For the sake of simplicity, we will not be changing the default background positioning area of the element in the rest of this article. So all of our examples will be applied to an element whose padding area is the area inside which the background is positioned.

Positioning Background Images Using background-position

We saw in the previous section how the background image is positioned by default at the top left corner of the positioning area. This is due to the fact that the default position value for the background-position property is 0% 0%.

The default position is a percentage value. You can supply background-position with either a percentage value or an absolute value, that specify the offset of the image from one of the positioning area’s four edges (top, right, bottom, left).

offset-edges-and-system

An element’s offset edges and coordinate system in CSS.

In addition to percentage and absolute offset values, five offset keywords exist and can be used: top, right, bottom, left and center.

A position can be described by specifying one offset value (keyword, percentage, or length), two offset values (a combination of two of the three possible values), or four offset values (a keyword and a relative numerical value). (We’ll talk about these in more detail in the upcoming sections.)

background-position: top left;
background-position: 50px 30%;
background-position: top 25%;
background-position: right 10px bottom 20px;
background-position: center center
background-position: 10px 20px;
background-position: 5em 2em;
background-position: 75% 50%;

If you provide only one value, the second one is assumed to be center. If you provide two values, the first one determines the offset from the left edge—i.e. the horizontal position, and the second one is the offset down from the top edge—i.e. the vertical position.

background-position: 10% 50%; /* 10% of the width to the right, and 50% down from the top */
background-position: top; /* equivalent to `top center` */
background-position: 50px; /* equivalent to `50px center` */

You can mix and match values, combining lengths with percentages and/or keywords. Note that a pair of keywords can be reordered while a combination of keyword and length or percentage cannot. So center left is valid while 50% left is not—it must be left 50%. When a combination of keyword and a length or percentage value is used, the first value always corresponds to the horizontal offset and the second value to the vertical offset.

As a matter of fact, the keywords are shorthand for specific percentage values. More specifically: top is equivalent to 0% offset from the top edge, bottom is equivalent to 100% offset from the top edge, left is equivalent to 0% offset from the left edge, and right is equivalent to 100% offset from the left edge and center is equivalent to 50% offset in whatever direction (horizontal or vertical) is it applied to.

Let’s start with how each possible value type works—this is probably the most important thing as there is a fundamental difference between the way absolute and percentage values are used by the browser to position background images. We’ll provide more examples as we go.

How Absolute Position Values Work

When you specify a position in absolute units, you’re offsetting the background image’s top left corner by the specified amount. In other words, the image will be moved so that its top left corner is positioned at the offsets specified in your background-position value.

The best way to explain and understand this is to visualise it, so here are two examples of absolute background position values and how they are interpreted by the browser to position the background image. The element in these two examples has 100px by 80px dimensions.

absolute-position-illustration

Positioning a background image using absolute values.

The absolute position can also be negative, in which case the image will be offset in the opposite direction from the edge.

negative-absolute-offset-illustration

Example showing an image offset using a negative offset position value.

Try changing the values of the background position in the following live example to see how the it affects the image. Try negative values too!

See the Pen Adobe background-position Example by Sara Soueidan (@SaraSoueidan) on CodePen.

How Percentage Position Values Work

Unlike the absolute length offset value which moves the element’s top left corner by a specified distance, a percentage X aligns the point at X% across (for horizontal) or down (for vertical) the image with the point at X% across (for horizontal) or down (for vertical) the container.

For example, the percentage value 0% 0% will align the point 0% 0% of the image with the point 0% 0% in the background positioning area’s coordinate system. The position value 50% 75% will align the point that is 50% across and 75% down the image, with the point that is located at 50% 75% in the background positioning area.

Again, a visual example explains it best. Notice how the position value specified is used to get the point of those coordinates inside the image and then aligns that point with the point of the same coordinates in the positioning area.

 

percentage-values-illustration

Positioning a background image using percentage values.

And as with absolute values, you can also specify the percentage offset in negative values, and those will move the background image by the specified value in the opposite direction of the corresponding axis. So a -10% -30% position will offset the image by 10% to the left of the left edge, and 30% upwards.

Play with the values in the following example to see how the background image position changes.

See the Pen Adobe background-position Example#2 by Sara Soueidan (@SaraSoueidan) on CodePen.


The positioning in the previous two examples is done relative to the top and left edges. Now let’s see how we can combine the offset keywords along with the numerical offset values (percentage or absolute) to position images across the background positioning area relative to any of the element’s four edges.

Offsetting Relative to Any Edge

In the examples from the previous two sections, we specified offsets and saw how they are used to offset the image with respect to the top and left edges—which is the default behaviour for one- or two-value positions.

When you combine offset keywords with numerical values for a four-value syntax, you can offset the background image from the right and bottom edges of the positioning area too.

In order to do that, all you have to do is specify the name of the edge you want to use followed by the amount (absolute or percentage) you want to offset it by.

For example, the following are examples of the four-value syntax:

background-position: top 1em right 3em; /* positions the background image 1em down the top edge and 3em left of the right edge */

background-position: right 1em bottom 1em; /* positions the background image 1em above the bottom edge and 1em to the left of the right edge */

background-position: left 20px bottom 50px;

If three out of four values are specified, the fourth value is assumed to be zero.

There is something to keep in mind when using the four-value syntax: When three or four values are given, then each percentage or length represents an offset and must be preceded by a keyword which specifies from which edge the offset is given. For example, background-position: bottom 10px right 20px represents a 10px vertical offset up from the bottom edge and a 20px horizontal offset leftward from the right edge. If three values are given, the missing offset is assumed to be zero. If your provide two numerical offsets and one keyword, the value is invalid and the browser uses the default 0% 0% value.

To get a better grip of this, play with the values of the background-position property in the following live example. The crane background image is first positioned so that it is offset by 0 pixels from the bottom and 2em from the right edge.

See the Pen Adobe background-position by Sara Soueidan (@SaraSoueidan) on CodePen.

This is particularly useful for when you need to position an image at a defined distance from the right and bottom edges, which makes this task much simpler than having to calculate the relative offsets from the top and left edges.

Sizing, Repeating, Clipping and More!

Remember, you can apply multiple background images to an element. For every background image (provided as a list of comma-separated images to background-image), you can specify a corresponding background position; multiple positions are also comma-separated.

All in all, there are nine CSS properties that control the layout, positioning, sizing and painting of background images, including the shorthand background property that is used to set and reset other shorthand properties. Each property allows you to do one thing, and combined they give us great control over how to apply background images to all and any element in HTML. I hope this article has demystified the way positioning background images in CSS works.

In addition to the main background properties, an additional property now exists that allows us to apply blending effects to background images similar to the blending effects available in editors like Photoshop—specifically, the background-blend-mode property. If you’re interested in learning all about blending in CSS, you can read more about it here.

I hope you found this article useful. Thank you for reading.

Comments (0)
Mar
05

Levelling Up With Sass

Posted by: | Comments (0)

Using a CSS preprocessor is fast becoming a crucial part of a developer’s workflow. If it isn’t part of your process yet, consider giving it a try! Check out part 1 of this series and get up to speed with basic features such as nesting selectors, variables and mixins.

Using preprocessors can help organize your CSS and reduce redundancy. However, learning more advanced features will make your CSS even more powerful.

This article will focus on stepping up your game with Sass, though many of these techniques will work using Less as well. Just be sure to note the syntax differences.

Nesting selectors

Nesting and grouping related selectors into one block can make your CSS more organized.

header {
    color: black;

    .logo {
        width: 300px;
    }
    nav {
        font-size: 12px;
    }
}

compiles to:

header {
    color: black;
}
header .logo {
    width: 300px;
}
header nav {i
    font-size: 12px;
}

But what about pseudo selectors or multiple class & id selectors?

a {
    color: #cc0066;

    :hover {
        color: #cccccc;
    }
}

The above example will compile to:

a {
    color: #cc0066;
}
a :hover {
    color: #cccccc;
}

Nested selectors are assumed to be a child element and will automatically add a space between selectors. This is not what we want for psuedo selectors or targeting multiple classes or ids. For this scenario, use the & symbol.

a {
    color: #cc0066;

    &:hover {
        color: #cccccc;
    }
}
.class-one {
    color: #cc0066;

    &.class-two {
        font-size: 16px;
    }
}

The above example will compile to:

a {
    color: #cc0066;
}
a:hover {
    color: #cccccc;
}
.class-one {
    color: #cc0066;
}
.class-one.class-two {
    font-size: 16px;
}

Reminder for nesting selectors, just like Inception, don’t go more than 3 levels deep!

Variables

Variables are super handy, especially for colors. It’s much easier to remember “orange” rather than “#E74C3C”, right? Suppose you decided to use orange as an accent to add a pop of color here and there throughout your web page. Your Sass may look something like this:

$orange: #E74C3C;

h4 {
  background: $orange;
}
a {
  color: $orange;
}

But what if you wanted to change that accent color to blue? You could create a new $blue variable and replace the existing color or change the value of $orange but then the variable name will be confusing!

Use variables as values

If you’re anything like me, I change my mind a lot, so I want my CSS to be able to bend to all my whims as easily as possible. Try using a combination of declaring style and functional naming conventions, then use the variables as a value of another.

$orange: #E74C3C;
$blue: #0000FF;
$primary-color: $orange;
$secondary-color: $blue;

h4 {
  background: $primary-color;
}
a {
  color: $secondary-color;
}

This way, I’m assigning the colors to the selectors based on their function, not the actual color. If I want to change the color, all I’ll have to do is update the variable value, in just one spot!

This technique can work great for font sizing as well, especially when paired with the math capabilities of the language to create relative sizing values.

$base-font-size: 1rem;
$main-heading: $base-font-size + 1; 
$sub-heading: $base-font-size + .5; 
$small-text: $base-font-size - .5;

body {
  font-size: $base-font-size;
}
h1 {
  font-size: $main-heading;
}
h2 {
  font-size: $sub-heading;
}
.footnote {
  font-size: $small-text;
}

The above will compile to:

body {
  font-size: 1rem;
}
h1 {
  font-size: 2rem;
}
h2 {
  font-size: 1.5rem;
}
.footnote {
  font-size: 0.5rem;
}

Comments

You can use two kinds of comment styles in your Sass files. The traditional CSS style, /* comment */ and also the double forward slash style // comment works as well. What’s the difference? The latter does not compile into the .css file. Which is handy for making your CSS files a little bit smaller. (You can also set your Sass compiler to minify your files as well.)

When using CSS preprocessors, you don’t need to edit your .css files anymore so there’s no need for the comments to compile out anyway.

Sass color functions

Some of my favorite Sass functions for creating various color values are lighten(), darken() and rgba().

In many web designs, you will often see variations of the same color. Instead of trying to find a new color value for each variation, use Sass functions!

$grey: #808080;
$grey-dark: darken($grey, 30); // 30% darker
$grey-light: lighten($grey, 10); // 10% lighter

body {
  color: $grey-dark;
}
.footnote {
  color: $grey-light;
}

The above example will compile to:

body {
  color: #343434;
}
.footnote {
  color: #9a9a9a;
}

Sometimes you will need to add an opaque background color to an element. The best way to achieve this without affecting the opacity of the text contained within that element using tradtional CSS, is to use rgba() as your color value like so:

div {
  background: rgba(173, 216, 230, 0.8);
}

The first three numbers represent the red, green and blue values. The last number is the alpha transparency.

What if your Sass variables have been declared in hex values, like in all the previous examples? You could go and find the equivalent RGB value. Or… use a Sass function!

The rgba(color, alpha) Sass function will automatically convert the value for you.

$orange: #E74C3C;
$blue: #0000FF;
$primary-color: $orange;
$secondary-color: $blue;

div {
  background: rgba($orange, 0.8);
}
span {
  background: rgba($secondary-color, 0.8);
}

Compiles to:

div {
  background: rgba(231, 76, 60, 0.8);
}
span {
  background: rgba(0, 0, 255, 0.8);
}

Mixins

And finally, we arrive to mixins. Mixins are handy for multiple CSS declarations that are used together often.

For example, I don’t like to reset all my lists as part of my base CSS but having that option to easily reset a list when needed, is useful. So I’ll create a mixin just for that.

@mixin list-reset() {
  padding: 0;
  margin: 0;

  li {
    display: inline-block;
  }
}
ul.specific-list {
  @include list-reset();
}

Will compile to:

ul.specific-list {
  padding: 0;
  margin: 0;
}
ul.specific-list li {
  display: inline-block;
}

You’ll still be able to add additional styles to that particular list, but using the mixin will make it a little easier to start.

ul.specific-list {
  @include list-reset();
  width: 100%;
}

Compiles to:

ul.specific-list {
  padding: 0;
  margin: 0;
  width: 100%;
}
ul.specific-list li {
  display: inline-block;
}

Mixins and conditionals

Pair mixins with parameters and conditionals to add even more efficiency to your style sheets. For media queries, try something like this:

@mixin max-width($resolution) {
  @if $resolution == large {
    @media only screen and (max-width: 1024px) { @content; }
  }
  @else if $resolution == medium {
    @media only screen and (max-width: 800px) { @content; }
  }
  @else if $resolution == small {
    @media only screen and (max-width: 400px) { @content; }
  }
}

@include max-width(small){
  .some-class {
    width: 100%;
  }
}
@include max-width(large){
  .another-class {
    width: 50%;
  }
}

Compiles to:

@media only screen and (max-width: 400px) {
  .some-class {
    width: 100%;
  }
}
@media only screen and (max-width: 1024px) {
  .another-class {
    width: 50%;
  }
}

Note the @content within the declaration block. In Sass, this directive simply allows
us to pass pretty much anything in between the curly braces, unlike parameters which are specific types of values.

You can use this example to create media query mixins for min-width as well as declaring a range.

These are just a few examples of how you can use Sass to take traditional CSS the next level. See the documentation on the Sass site for even more ideas.

Now that I’ve listed some of my favorite Sass features, please share your favorites in the comments!

Comments (0)

Like most of our ‘Your Questions Answered’ posts, we’re going back to the basics. We get all kinds of questions from our users on our forums, Twitter and Facebook. One question that has come up a bunch, which we’ll be covering in this post, is around creating a table and centering objects using HTML and CSS.
Users that have previously styled tables using HTML will find this tutorial relatively simple. However, if you are new to HTML and CSS, you can still create this table without too much effort. We are using Dreamweaver CC for this tutorial.

Let’s get started.

Create a new page

  1. Open Dreamweaver
  2. Select File > New
  3. In the New Document dialog box, ensure that HTML is selected as the Page type.
  4. Click Create.
  5. In the Code view, locate the tag. In between the opening and closing title tag, enter “Centering objects in a table”.
  6. Select File > Save As and save the file as centering_tables.html.

Create a container for the table

Before we proceed with creating a table, we will be creating a container div tag (containerDiv) to hold the contents of the page, and another container in which we will be placing the table (tableDiv). In the Code editor between the body tags, enter the following code:

<body>
<div class="containerDiv">
<div class="tableDiv">
</div>
</div>
</body>

We now have a container for the contents of the page, and our own DIV for the table that we will be creating now.

Create a table using HTML

Inside the tableDiv container, create a table. Enter ‘Hello’ in each of the cells so that we can see the table clearly in the Design or Live view.

<table>
<tr>
<td>Hello</td>
<td>Hello</td>
<td>Hello</td>
</tr>

<tr>
<td>Hello</td>
<td>Hello</td>
<td>Hello</td>
</tr>
</tr>
</table>

In the Live View or Design View, you should now be able to see a 2×2 table with ‘Hello’ placed in each of the cells. You should also be able to see the container div that is enclosing the table.

hello_code

Style the table

Below the closing title tag, create the opening and closing style tags. Then, use this piece of code to style the table. In the following piece of code, the border-collapse property creates a single continuous border for the table. The rest of the properties are self-explanatory.

.tableStyle{
	border: thin solid #EFEFEF;
	border-collapse:collapse;
	width: 800px;
	margin: 0 auto;
	text-align: center;
	align-items:center;	
	}

In the body, apply the style to the table tag.

Preview the file in a browser using File > Preview in Browser. You should now be able to see the table centered on the page and with a light gray border.

hello_cod2e

Style the cells in the table

We now need separators for each of the cells in the table. Let’s work on that.
Right below the tableStyle in the Style section of the code, enter this piece of code.
Padding will ensure that the text within the cell gets some breathing space.

.tableCell{
	align-content: center;
	border-width: thin;
	border: thin solid #EFEFEF;
	padding: 5px;	
	}

Ensure that you apply the style to all the cells in the table.

Preview your page in a browser. Does it look like this?

hello_code3

The page is centered in its container, and the contents of the table are centered as well.
One last thing you may want to do is to center the entire page in a browser. In which case, we will use this piece of code that we used to center a page.

.containerDiv{
	width: 1200px;
	margin: 0 auto;
		}

And you are done! Check to make sure you got everything right by looking at the final result. Then go ahead and play around with your table. Apply styles, add images, do your thing. Have fun!

Comments (0)

If you use Sass or LESS, then you probably already use variables in your style sheets and know how useful they are. If you don’t use a preprocessor, then you might be curious what the fuss is all about and why variables are so popular and how they can be useful. In this article, we’re going to get an overview of why variables are useful, and get acquainted with one particular variable: currentColor.

What are variables good for?

Variables in CSS are useful because they allow us to write more DRY (Don’t Repeat Yourself) code. They are also particularly useful for managing and maintaining large-scale projects that contain a lot of repeated values.

One of the most common use cases for variables are color themes/schemes throughout a website or application. With variables, creating and managing color schemes across a CSS document becomes a lot easier. For example, color schemes usually require you to reuse a few color values for different properties in the CSS file. If you want to change the primary color of a scheme, you would normally have to change all occurrences of that color in the style sheet. Using CSS variables, you can define a variable in one place (for example a variable named “primary-color”), assign a color value to it, and then use the variable as a value anywhere you want in the style sheet. Then, when the time comes to change this color, all you would have to do is assign it a different color value, and all occurrences of that variable in the style sheet will be automatically updated.

CSS 2.1 did not introduce variables. (Although, that’s not entirely true, as you will see in this article.) In 2014, native CSS variables that are similar to preprocessor variables were introduced; these variables are arguably even more capable than preprocessor variables. A CSS variable is accepted as a value by all CSS properties.

In addition to the new variables, CSS already comes with a keyword value that is practically also a variable: the currentColor keyword.

The currentColor keyword

The currentColor keyword is like a CSS variable, except that it has one main restriction: you can only use it where a <color> value is expected; if a property does not accept a <color> value, it will not accept currentColor as a value.

The following are all examples of using currentColor in properties that accept it as a value.

box-shadow: inset 2px 2px 3px currentColor;
background-color: currentColor; /* not a good idea! */
background-image: linear-gradient(currentColor, transparent);

Another difference between currentColor and other variables is that you don’t get to assign a value to it the same way you would assign other variables values. The value of currentColor is determined by the computed value of the color property that is currently being used on the element. That is, the value of currentColor is equal to the current color property value. And this is where the currentColor name comes from.

So, if we were to go back to our previous example, the currentColor keyword sets the box shadow color to whatever color value you have set on the div. If you haven’t set any color, it will use the inherited color from any of the div’s ancestors. If no ancestor has a color, most browsers will just default to black.

Put another way: the currentColor keyword is used to make properties of an element, or child elements of an element, inherit the color set by the element’s color property. It therefore acts as the inherit value to allow inheritance of a color that would otherwise not be inherited by a property or child element.

This also means that, for properties that already inherit the color value, currentColor will not be of much use.

Properties and elements that inherit the color value by default

When an element has a color value, whether it is explicitly set or inherited, some of the foreground elements of that element that accept a <color> value will inherit that color value by default.

For example, an element’s borders are part of the element’s foreground; thus, even if you don’t specify a border color, the border will get the same color as the color property value. If the element does not have one, most browsers usually default to black.

The border color in this example will be purple:

.parent {
    color: purple;
}

.child {
    border: 5px solid; /* we didn’t specify the border color here */
}

The elements that will get/inherit the element’s color value include:

  • The element’s text—it is what the color property is used for.
  • The text’s outline.
  • The element’s border.
  • The element’s box shadow.
  • An img’s alt text. That is, when the image cannot be displayed, the text that appears in its stead will have that color value.
  • A list item’s bullet(s) and border.
  • In some browsers (e.g Chrome) the horizontal rule’s (<hr>) border color. (Without a border, the color will not be affected.)

When you set these element’s properties on an element without explicitly assigning them a color, they will inherit the computed color value of the element by default.

The following demo shows the above elements in action as they inherit the color set on the page’s body. Change the color property value on the body to see these elements’ colors also change.

See the Pen currentColor — Adobe DW Blog by Sara Soueidan (@SaraSoueidan) on CodePen.

At this point, you might be wondering: if so many properties/elements already inherit the color value, how or where can currentColor be useful?  

Extending color inheritance with currentColor

There are some places where retrieving the color value and using it could come in handy. One example where currentColor can be used that would not otherwise inherit the color value is gradients. CSS gradient images, be that linear or radial gradients, do not inherit colors. By using currentColor, you can make a linear gradient used as a background image, for example, adjust to match any color you specify somewhere else as the “primary color” of a theme.

background-image: linear-gradient(to bottom, currentColor, #fff);

Such an example was created by Scott Kellum who took this concept a little further and added an animation to the color property. As the color property animates, all the elements affected by that color will also animate their colors.   See the Pen currentColor by Scott Kellum (@scottkellum) on CodePen.

This is a great example of using currentColor, particularly the animation part.

However, more practical examples for currentColor exist. Let’s take a look at some of them.

currentColor Use Cases

The idea behind currentColor is to extend the color cascade. This comes in handy in a lot scenarios.

currentColor for theming UI components

From the previous demo, we can move to a more practical (and brilliant, I must say) use case for currentColor demonstrated by Simon “Simurai” in a talk he gave at CSSConfau last year. The talk was about how we can use Flexbox, currentColor and em units inside UI components to quickly style entire Web Apps straight in the browser.

To demonstrate the usefulness of currentColor, Simon created a set of UI elements, including some sliders. These elements have the same color scheme applied. For coloring the sliders and input types, he used the currentColor variable to force the color inheritance in the background color of the slider’s thumb and checkboxes that would otherwise not inherit that color.

currentColor-slider

An example using currentColor to apply the color property’s value to the slider’s thumb. (Source)

Similarly, more UI components can be created that inherit a color value that you would specify somewhere up in the cascade. With this, a UI theme is established on these components. Then, leveraging the cascade and currentColor, you can change the main color value and get a new set of colored components every time you do, thus practically automating the process.

The following GIF image shows that in action. Simon is using the browser devtools and the color picker in the browser to change the value of the color property, and get a live preview of these changes on the components.

Changing the value of the color property will update the colors of all UI components that are inheriting this color, with the help of the currentColor variable. (Source)

 

Using the browser’s devtools capabilities, you would be able to change the theme to your liking and then save the changes to your working files right from the browser. To learn all about it, refer to Simon’s talk and blog post.

currentColor for theming and styling SVG

SVGs are great, but they come with a few styling quirks and limitations depending on how you use them. One such case is reusing parts of an SVG using the SVG <use> element.

If you’re not familiar with the <use> element, you can read all about it here. The idea behind <use> is to reuse parts of an SVG anywhere we want these parts to appear on the page. By useing an SVG element, we’re practically creating a live copy of that element. This is similar to copy-pasting the element in a graphics editor, except that the copy is live—meaning that its characteristics can change as the original copy changes.

The <use> element is used a lot when creating SVG sprites. An SVG containing all of the icons would be used as the sprite, and then we can insert individual icons from that sprite anywhere on the page, using <use>. You can read all about SVG creating sprites in this article.

When an element is used, however, the copy of its contents is cloned into a shadow DOM. This means that these contents cannot be selected and styled with CSS the way we would select and style SVG elements or even HTML elements present in the regular DOM. This is one reason why styling SVG icons created like that is limited.

Using currentColor, we can work around this limitation but allowing a color we specify in CSS “leak” into the contents of the used SVG, by setting currentColor as a value for the properties we want the color value to leak into.

So with an SVG icon used like so:

&lt;svg class="home-icon"&gt;
    &lt;use xlink:href="#home"&gt;&lt;/use&gt;
&lt;/svg&gt;

And assuming the #home icon defined in the sprite sheet contains something like:

&lt;symbol id="home"&gt;
    &lt;rect id="bottom" fill="currentColor" ... /&gt;
    &lt;polygon id="roof" ... /&gt;
&lt;/symbol&gt;

We can then apply styles to the icon and have the fill color cascade down to the #roof (which does not have a fill attribute above) and the color value be inherited by the #bottom rectangle’s fill attribute:

.home-icon {
    fill: red;
    color: white;
}

The fill color will cascade down from the svg to use and then to #roof. The color value will be used as a value for the #bottom fill color because of currentColor.

Fabrice Weinberg wrote an article about this technique a while back on his Codepen blog.

This technique comes in handy when you want to create multiple icons each having different colors; all you would have to do in that case is change the color and fill values in the CSS. An example of this usage is the following demo Fabrice shows in his post:

See the Pen Sass SVG Icons 1.1KB by Fabrice Weinberg (@FWeinb) on CodePen.

Of course, you can use currentColor on multiple elements inside the SVG. However, as you probably have noticed, this only allows you to change two colors inside the SVG.

If you want to have more control over colors and specify more color values that you could leak into the SVG, you would need more variables; this is where the new CSS Variables specification will come in handy. You can read more about this here.

Final Words

In the previous examples, we saw how we can use currentColor in multiple places, and then change the colors we want in one place and have that color be applied to those multiple places, instead of having created multiple occurances of the same color and then changed all of them. This helps us write shorter CSS, and provides us with some sort of automation, especially in situations like the UI components we saw in Simon’s talk.

With CSS Variables, you will be able to define your own set of variables and use them in similar and much, much more use cases, as the new variables will be valid values for any CSS property, not only those that accept <color> values. Dealing with SVG icons will certainly become easier, as will maintaining large-scale projects. Again, if you use a preprocessor, then you already know how useful variables are.

Can you think of more use cases for currentColor? If so, make sure you share them in the comments below!

Comments (0)

We have received a number of requests from Dreamweaver users about creating menus, and we’re here to help! In this ‘Your Questions Answered’ post we’re tackling the basics of creating a menu in Dreamweaver. We’ll get more advanced in later posts, exploring how to create drop down menus and responsive menus, but for now let’s get started with a solid foundation to build off of.

If you are new to Dreamweaver, see our previous ‘Your Questions Answered’ post which walks you through setting up a site in Dreamweaver. Once you have a site set-up, you’re ready to rock this tutorial.

Let’s get coding!

Create a new page in Dreamweaver

  1. Select File > New
  2. Choose the default option (HTML), and click Create.
  3. Select File > Save As and save the file as menu.html

Create an unordered list in the body of the HTML page

Your code should look something like this:

<body>

<ul>

 <li><a href="home.html">Home</a></li>

 <li><a href="about.html">About</a></li>

 <li><a href="careers.html">Careers</a></li>

 <li><a href="contactus.html">Contact us</a></li>

</ul>

</body>

 

Depending on the view that you are in, you should be able to see an unordered list in the Design View or Live view. Notice that each item in the list is associated with an <a> tag. You specify the destination for each item in the <a> tag. For example, when you click Home, the browser opens the home.html page.

We have not yet created the destination pages. So, clicking the links now will not lead you anywhere.

unstylized_menu

Remove the bullets from the list

You do not want bullets in your CSS menu, but never fear. We we will be using CSS to take care of this! After you are done with the code, click the Design view. The bullets in the list should disappear leaving you with a clean list.

Just below the <title> tag, create the style tags:

<style></style>

Insert this piece of CSS code in between the style tags.

ul {

       list-style-type: none;

       margin: 0;

       padding: 0;

}

list-style-type:none: removes the bullets from the ordered list.

Setting margins and the padding to 0 overrides any browser default settings.

Specify a width for each of the list items

If we do not specify a width for the list items, they will take up a default width. To specify the width, we will be specifying a style for the <a> tag associated with each item in that list.

Below is the CSS code for the ul tag. Insert this piece of code:

a {
    display: block;
    width: 60px;
}

display:block: This makes the whole area around the link clickable, not just the text.

By specifying the width at 60px, we are overriding any default width settings of the browser.
You will not notice any major change in the design view except for a border around each item in the list.

Lining up the menu items

Since we are creating a horizontal menu, we want to line up the menu items next to each other. To do this, we have to first remove the line break that is associated with each item. While you don’t see the line break in the code, each block element is associated with a line break before and after the item.

To do this, use:

li {
    display: inline;
}

Good, now the line breaks are gone. You won’t see anything happening in your Design view, but that’s okay. By default, each of the items take up the entire width of the browser. When we float them to the left, we tell each of those items to move to the left and make space for the next item in the list to move up and take up the empty space on the right.

li {
    display: inline;
    float:left;
}

You should now have the menu items lined up next to each other. Perfect.

linedup_menu

Styling the menu items

The menu is in place now, but it has no color and you don’t see anything happening when you move over each of the menu items. Let’s fix that!

Defining the style for normal and visited states

When browsing the Internet, you have likely seen instances where the color of menu items changes after you have clicked on and visited the page associated with the menu item link. It is a visual indicator letting you know that you have made at least one visit to that page previously.

While that is a good idea for normal links, it’s not a great option for menus. We do not want our menu changing color after a user visits a page. So, we are going to disallow that change.

An <a> tag or tag associated with links has four states:

a:link – a normal, unvisited link
a:visited – a link the user has visited
a:hover – a link when the user mouses over it
a:active – a link the moment it is clicked

Delete this piece of code:

a {
    display: block;
    width: 60px;
}

Now enter this code in between your style tags:

a:link, a:visited {
    display: block;
    width: 120px;
    font-weight: bold;
    color: #FFFFFF;
    background-color: #98bf21;
    text-align: center;
    padding: 4px;
    text-decoration: none;
    text-transform: uppercase;
}

Now, the style for the normal and visited states of the menu have been defined. Look in your design view. You should see something like this:

menu

Defining the style for the hover and active states

Let’s keep things simple. We don’t want two different things happening when the user moves the mouse over the link and when they try to click it. We want the same style for both actions. All we will do is change the background color for these states.

Changing the background color lets the user know the menu item that is being clicked.

a:hover, a:active {
    background-color: #7A991A;
}

Preview your menu in a browser

You should be able to see the effects when you move your mouse over each of the menu items. However, because those pages do not exist, nothing actually happens when you click on those links. You will have to create each of those pages and add some content to them to see the menu in action.

Centering the menu

To center the menu, we will associate an ID with the

    tag, and then style the ID.

In the body, your code should look something like this:

<ul id="nav">
  <li><a href="default.asp">Home</a></li>
  <li><a href="news.asp">News</a></li>
  <li><a href="contact.asp">Contact</a></li>
  <li><a href="about.asp">About</a></li>
</ul>

Now that the association has been taken care of, let’s stylize the nav ID. We will use pretty much the same trick that we used to center a web page in a browser.

#nav{
    width:750px;
    margin:0 auto;
  }

With this code we have defined a width for the container, set the top and bottom margins to 0, and the left and right margins to auto. This clears the space to the left and right of the margin allowing the browser to calculate the margin.

Not sure if you got everything right? Take a look at a completed source file.

Until next time, happy coding!

Comments (0)

Instead of linking to new pages, sometimes links (`<a>` elements) reference sections, fragments or other elements of the same page. These kind of links are prevalent in one-page website navigation.

The CSS `:target` pseudo-class selector is used to select and style the target of an internal link in a document, the fragment of the page referenced in a link’s `href` attribute.

For example, if you have an anchor tag linking to a “further reading” section of an article…

<a href=“#further-reading” title=“Further reading resources” />

<!– … –>

<section id=“further-resources”>

<!— … —>

</section>

…you can use the `:target` selector to highlight this section when the link is clicked to guide the reader’s eye to it. This highlighting technique is known as the yellow fade technique and was first introduced by 37 Signals.

#further-resources:target {

animation: highlight .8s ease-out;

}

@keyframes highlight {

0% { background-color: #FFFF66; }

100% { background-color: #FFFFFF; }

}

The technique requires that you use a CSS animation to show the color for only a short period of time and then remove it again—the point is to highlight it only enough to guide the reader to it. Check out the live demo showing this technique in action:

See the Pen ogBWmL by Sara Soueidan (@SaraSoueidan) on CodePen.

The above example applied temporary styles to the target of the link. But if you apply more persistent styles, you can create effects scaling elements up, changing their visibility, and much more.

I have recently used this technique on my own website to show a search overlay for my readers to search for articles in. As part of the main navigation, there is a link that links to the search overlay wrapper—a `<div>` element, containing the search input field.

<a href=”#search”>Search</a>

<!– … –>

<div id=”search”>

<a href=”#” class=”overlay-close”>Close</a>

<h4>Search articles archive.</h4>

<!– … –>

</div>

The search overlay is initially hidden using `opacity: 0;`. It is positioned so that is remains fixed relative to the viewport using `position: fixed;`. And in order to make sure that it doesn’t block pointer events from the rest of the page “beneath” it, `pointer-events` are set to `none`.

 #search-overlay {

position: fixed;

top: 1em;

bottom: 1em;

right: 1em;

left: 1em;

/* … */

opacity: 0;

transition: opacity .3s ease-in-out;

pointer-events: none;

}

Once the Search anchor is clicked, and using the `:target` selector, the overlay is shown and pointer events are dispatched on it again. In order to show the overlay smoothly, a transition is applied that creates a fading in effect.

#search-overlay:target {

opacity: 1;

pointer-events: auto;

}

The search overlay fades in. Mission…half accomplished—we need to make sure it fades out again when the user requests so.

The overlay container needs to contain another link that will allow us to go back to the main page. To do that, we could give the `body` or `html` element an ID, and then have the Close link to that ID—this would do it. However, that is not necessary. By linking to no particular fragment using only the `#` as a value, you’re practically linking to the main page, but you gain the advantage of not adding any fragment identifier to your page’s URL.

Once the Close link is clicked, we want the search overlay to fade out, so we’re going to add a transition again to the `#search-overlay:target` to make sure its opacity transitions to `0`. You can, of course, avoid this step if you just want to make it disappear instantly when the user closes it.

#search-overlay:target {

opacity: 1;

pointer-events: auto;

transition: opacity .3s ease-in-out;

}

Check out the live demo.

You can take it further and add a transformation animation to the overlay so that it scales up into view as it fades in—kind of like (yes, you guessed it) a Lightbox effect. Instead of an overlay with a search form, you could have an image that would scale into view when its respective thumbnail is clicked. Manoela Ilic has a nice and complete working image gallery showing this in action, with a tutorial explaining the code behind it.

Christian Heilmann also wrote a post about creating a simple image gallery using the `:target` selector that is also worth checking out.

CSS-only image galleries, modals, and off-canvas navigation, are  all examples of fully-functional UI components that you can create using only CSS, by taking advantage of the the `:target` selector.

I hope this introduction helped show you to the possibilities at hand when using and styling content with CSS pseudo-class selectors.

More to come! ;)

Comments (0)

Using CSS to create drop caps in your design can be cumbersome. If you’ve used dropcap.js, you know it’s a much easier way to realize your design. The good news? We’ve made it even easier for Dreamweaver CC users with a native dropcap.js extension called Dropcaps.

Now you can enlarge the first letter of a paragraph or section of text to catch readers’ attention and jazz up your design.

 

Dropcap first character

Dropcap first character

 

Let’s take a look how you can do that in a few easy steps:

Installing the Dropcaps extension

  1. Quit Dreamweaver CC.
  2. Make sure you have installed the Creative Cloud Desktop App. 
  3. Make sure sync-files feature is turned on and not paused. 
  4. Make sure you have installed a compatible Adobe application.
  5. Install the Dropcaps extension from the Adobe Add-ons page.
  6. Check that you have acquired your Add-on.
  7. Restart Dreamweaver CC 2014.1 so that the Add-on can be enabled.


Using the Dropcap extension

  1. Launch Dreamweaver CC.
  2. Open your web page in Dreamweaver.
  3. Select the required paragraph:
    • If you are in Live View, simply click the text element.
    • If you are in Code View, position the cursor inside the text or tag, or select the text.
  4. Open the Dropcaps extension dialog box by selecting Window > Extensions > Dropcaps, or by using the Keyboard shortcut = Cmd+Alt+L on Mac; Ctrl+Alt+L on Windows.
  5. Specify the following details in the Dropcaps extension dialog box (see Figure 1):
    • Height: Number of lines that the height of the drop caps element spans. Counting is from top to bottom.
    • Baseline (optional): The line number to which the base of the drop caps element aligns with. Counting is from top to bottom. (Default value: same as height)

No. of characters (optional): The no. of characters to which the drop caps effect should be applied. (default: 1)

Dropcaps Extension

Dropcaps Extension

 

  1. Click “OK”.
  2. File > Save to confirm changes.

 

Note: An ‘extDropcaps’ folder gets created in the same directory as your web page. This folder contains the JavaScript for the drop cap effect, and needs to be uploaded to your publishing server along with the rest of the files and scripts.

To edit the drop cap’s properties, select the text element, open the Dropcaps extension, and edit its values.

That’s it! You’re done. Please follow us on Facebook or Twitter so you can always get the latest Dreamweaver news.

Best,

The Dreamweaver Team

 

Comments (0)

The latest release of Dreamweaver CC has not only introduced new features but also has major improvements to existing ones such as the CSS Designer and the Element Quick View. We’ve created a couple of videos to provide an overview of these features and the enhancements we’ve made in Dreamweaver CC.

CSS Designer

This video provides an overview of the CSS Designer panel and highlights the improvements to it. In this video you’ll learn how to:

  • Start a page design with the CSS Designer.
  • Work with the CSS Designer visual controls.
  • Use the panel’s workflow enhancements.

You’ll also take a look at how Live View integrates with the CSS Designer feature, making web design easier than ever.

Element Quick View

The Element Quick View panel lets you easily modify the HTML structure of your page with a tree view.  In this video you’ll get an overview of the feature and learn how to:

  • Use the Element Quick View to precisely insert elements into your website.
  • Easily edit the structure of your website.
  • View editable and dynamic (read-only) elements.

 

Where to go from here?

Download Dreamweaver CC and give these features a spin. Adobe has published thousands of free learning tutorials and videos for all skill levels: beginners, intermediate, and advanced. We encourage you to continue to provide your feedback and input as this is what shapes our products.

Best,

Dreamweaver Team


Comments (0)

Database Design and Management

Cwebpro can design and develop a small business data management solution for you. We will provide professionally crafted entry screens and a database that will grow with your business.

Professional Web Designs

If you need a web site designed or updated contact Matthew at Cwebpro for quality work at a fair price. The Web Creation Zone (Cwebpro) can meet all of your business website design and data management needs.