Blog posts under the Sass tag https://webdevstudios.com/tags/sass/ WordPress Design and Development Agency Mon, 15 Apr 2024 16:05:03 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://webdevstudios.com/wp-content/uploads/2022/07/cropped-wds-icon.white-on-dark-60x60.png Blog posts under the Sass tag https://webdevstudios.com/tags/sass/ 32 32 58379230 Sass Tips to Take Your Skills to the Next Level https://webdevstudios.com/2019/12/03/10-sass-tips/ https://webdevstudios.com/2019/12/03/10-sass-tips/#comments Tue, 03 Dec 2019 17:30:36 +0000 https://webdevstudios.com/?p=21296 If you’ve been using Sass for a while, but find yourself writing seemingly basic code that doesn’t look very different from vanilla CSS, then this article is for you. We’ll explore ten ways to put Sass to use, taking advantage of some of its more intermediate to advanced features. Year after year, I continue to Read More Sass Tips to Take Your Skills to the Next Level

The post Sass Tips to Take Your Skills to the Next Level appeared first on WebDevStudios.

]]>
If you’ve been using Sass for a while, but find yourself writing seemingly basic code that doesn’t look very different from vanilla CSS, then this article is for you. We’ll explore ten ways to put Sass to use, taking advantage of some of its more intermediate to advanced features. Year after year, I continue to be impressed with the language’s capabilities and would like to share some of the tricks I’ve learned. This article assumes you have at least some working experience with Sass. If not, get your hands dirty with one of the many great resources on the internet. The Sass documentation is a great place to start. They don’t call them Syntactically Awesome Style Sheets for nothing, so let’s get started on these 10 Sass tips created to take your skills to the next level.

1. Parent Selector

Select a parent from within the child selector.

SCSS

View the code on Gist.

Instead of having to make a new selector for .container .text outside of the .text block, you can just write your selector inside of .text, followed by the &.

Compiled CSS

View the code on Gist.

HTML

View the code on Gist.

View on CodePen.

 


2. Suffixes

Here’s a cool way to generate suffixes based on a particular class. Use &- followed by the desired suffix. In this case, &-pink will create .container-pink when it’s used inside of .container.

SCSS

View the code on Gist.

Compiled CSS

View the code on Gist.

HTML

View the code on Gist.

View on CodePen

 


3. String Interpolation

String interpolation will render the result of a SassScript expression as compiled CSS. In this basic example, we’re setting color variables, then rendering them out as CSS comments.

SCSS

Notice how we use string interpolation directly in the comment.

View the code on Gist.

Compiled CSS

View the code on Gist.

View on CodePen


4. Placeholders

Placeholders are similar to variables in that they aren’t compiled in the actual CSS. The benefit of this is that they keep your code clean by rendering only the output of the placeholder. They can be extended anywhere in your code. Placeholders can be useful when you want to extend some particular properties across multiple selectors. Start your placeholder with a percentage sign %, so for example you could write %my-placeholder, and extend it inside your selector with @extend.

SCSS

View the code on Gist.

Compiled CSS

View the code on Gist.

HTML

View the code on Gist.

View on CodePen


5. Default value in mixins

When using a mixin, you normally need to pass in every argument that will be required. The advantage of using a default value is that you aren’t required to pass an argument in, but you can always override the default you’ve set. In this Sass tip example, I’m overriding the defaults for the second h1 as I pass in an argument of darkcyan.

SCSS

View the code on Gist.

Compiled CSS

View the code on Gist.

HTML

View the code on Gist.

View on CodePen


6. Null

Let’s expand on what we just did with using a default value, except this time, we’ll use null as a default value. If no arguments are passed in, nothing will be compiled in the CSS for opacity, but if an argument is passed in, it will be compiled in the CSS. This is a nice trick because your CSS won’t be bloated with unused styles.

SCSS

View the code on Gist.

Compiled CSS

View the code on Gist.

HTML

View the code on Gist.

View on CodePen


7. Color Functions

Color functions open a world of options for manipulating colors. They are built into Sass and can be used to dynamically generate CSS based on your needs. Here, we instantiate our scale-color function, passing in a color, and a saturation percentage. There are many color functions, and I encourage you to experiment with them.

SCSS

View the code on Gist.

 

Compiled CSS

When compiled, the hexidecimal color here is the result of the expression.

View the code on Gist.

HTML

View the code on Gist.

View on CodePen


8. @if to Change Contrast

Here’s a great Sass tip: Sass has control flow built into it. There are four types of control available to use: @if, @each, @for, and @while. Here, we use an @if conditional to determine if our colors meet the desired threshold for contrast; we then render the text color based on the outcome.

SCSS

View the code on Gist.

Compiled CSS

View the code on Gist.

HTML

View the code on Gist.

View on CodePen


9. @debug

When using Sass, there may be times when you need to know the value of an expression. If you use JavaScript, you have probably used console.log() to print the results of an expression to the console. The good news is that Sass has something similar. For example, it might be more work than it’s worth to figure out the saturation of #e1d7d2 yourself, but @debug is happy to do the math for you, right in the console!

SCSS

View the code on Gist.

Compiled CSS

View the code on Gist.

View on CodePen


10. Use @for to Build Your Own Utility Classes

You can even use loops in Sass. @for is one of the four types of control flow currently in Sass. Here, we’re going to generate some utility classes. We’re using the unquote function to return a string of "px", but without quotes. As you might be wondering, there’s also a quote function, which will return the same thing, but with quotes, of course. Note the use of string interpolation.

SCSS

View the code on Gist.

Compiled CSS

View the code on Gist.

HTML

View the code on Gist.

View on CodePen


Here’s a full list of all the CodePen examples for you to explore:

1. Parent Selector
2. Suffixes
3. String Interpolation
4. Placeholders
5. Default value in mixins
6. Null
7. Color Functions
8. @if To Change Contrast
9. @debug
10. Use @for To Build Your Own Utility Classes


Thank you!

Thanks for taking the time to read these Sass tips. I hope you’ve found some of these items that I’ve picked up over the years to be useful for your daily Sass workflow.

The post Sass Tips to Take Your Skills to the Next Level appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2019/12/03/10-sass-tips/feed/ 1 21296
Get Loopy with Sass https://webdevstudios.com/2017/02/07/get-loopy-sass/ https://webdevstudios.com/2017/02/07/get-loopy-sass/#respond Tue, 07 Feb 2017 17:00:53 +0000 http://webdevstudios.com/?p=16553 Whether you use Sass/SCSS, Less, or Stylus to compile your CSS, one thing’s for certain; it just makes life much easier. These preprocessors give us access to variables, necessary calculations, and powerful mixins that allow us to take our front-end workflow to the next level. As time passes the projects I tackle tend to present Read More Get Loopy with Sass

The post Get Loopy with Sass appeared first on WebDevStudios.

]]>
Whether you use Sass/SCSS, Less, or Stylus to compile your CSS, one thing’s for certain; it just makes life much easier. These preprocessors give us access to variables, necessary calculations, and powerful mixins that allow us to take our front-end workflow to the next level.

As time passes the projects I tackle tend to present questions that require unique answers — answers that don’t always need a PHP or programmatic approach; found in the lesser known (or utilized) parts of Sass: control directives. Similar to PHP or Javascript, Sass has if(), @if, @else, @else if, @for, @each, and @while that we can use to conditionally define or loop through styles using booleans or multiple variable checks. Why not save time and energy and make our compiler do the heavy lifting? You could even, in theory, automate the styles for an entire page or global elements. Let’s start off with the basics and end with a bang, then get into something more advanced.

if()

if() is a boolean expression that only returns one of two possible values: true or false, and it works like this.

if(true/false, true, false);

So a use case for this might be:

$boolean: false;

.text-color {
    $color: if($boolean, #000, #fff);
    color: $color;
} // .text-color

Which would output this:

.text-color {
    color: #fff;
} // .text-color

That’s pretty simple. I’ve found this useful when building two containers with same styles, with the exception that their colors are inverted. Using if() checks I can define either white or black depending on div-specific boolean variables.

@if and @else

@if is different than if(), though it is still a boolean, if() is a singular check, while @if evaluates a statement and runs code depending on the outcome. When used in conjunction with@else you can create a loop to allow for multiple checks for true as well as a default should all prior nested statements prove false.

Let’s build on the example above:

$text: #fff;
$boolean: false;

.text-color {

// Internal variables.
$color: if($boolean, #000, #fff);

// Determine background-color.
@if $text == #000 {
    background-color: #fff;
} @else {
    background-color: #000;
}

color: $color;
} // .text-color 

Notice here we’re using ==, but just like Javascript or PHP you have the whole list of operators to choose from including arithmetic (+ - * / %), equality (== !=), logical (and or not), and comparison (> >= < <=) to determine whether or not a statement is true or false.

Bonus: If you want to up your game check out string and color operations.

Which would output this CSS:

.text-color {
    background-color: #000;
    color: #fff;
} // .text-color

Though it does essentially the same thing, we allow for multiple conditionals and multiple possible outcomes with a few lines of code and one variable. A real time saver, and in my opinion, easier to read than a standard if() clause.

We can also do multiple @if checks with @else if, for example:

@if $text == #000 {
    background-color: #fff;
} @else if $text == #fc0 {
    background-color: #69ace5;
} @else if $text == #273143 {
    background-color: #ccc;
} @else {
    background-color: #000;
}

Tip: Remember that numbers, letters, and variables are case sensitive when doing checks.

@for

For those of you familiar with Javascript and jQuery, this might not be unfamiliar, but who knew?

@for can be used two ways looping from x “through” y or from x “to” y. “through” starts and iterates to and including the last item while “to” iterates and does not include that one last iteration.

Here’s a simple @for loop to help us generate helper classes for a grid framework:

@for $i from 1 through 4 {
    $width: 1 / $i;

    .col-#{$i} {
        width: $width;
    } // .col-#{$i}
} // end @for

This would output to:

.col-1 { width: 100%; }
.col-2 { width: 50%; }
.col-3 { width: 33.33%; }
.col-4 { width: 25%; }

Perhaps a more advanced usage might be to define the number of columns before you loop. You could also define mixins inside of the loop. Let’s take bourbon for instance.

$num-columns: 4;

@for $i from 1 through $num-columns {

    .col-#{$i} {
        @include span-columns( $num-columns / $i );
    } // .col-#{$i}
} // end @for

Would output to this:

.col-1 { 
    float: left;
    display: block;
    width: 100%;
}
.col-2 { 
    float: left;
    display: block;
    width: 48.8217%;
    margin-right: 2.35765%;
}
.col-3 { 
    float: left;
    display: block;
    margin-right: 2.35765%;
    width: 31.76157%;
}
.col-4 { 
    float: left;
    display: block;
    margin-right: 2.35765%;
    width: 23.23176%;
}

Note: If I was creating a grid, I might even add conditionals to make .col-1 output @include fill-parent; or even add &:nth-child(x);to remove the margin-right from the last item in a column row.

@each

each() works like you’d expect: @each $variable in <list or map>. You can loop through custom-defined class names to define a color or image (example below), which makes styling similar items a snap.

$type: action, western;

@each $movie in $type {
    .#{$movie}-container {
        background-image: url("assets/images/#{$movie}-bg.jpg");
    } // .#{$movie}-container
} // end @each

Output:

.action-container {
    background-image: url("assets/images/action-bg.jpg");
} // .action-container

.western-container {
    background-image: url("assets/images/western-bg.jpg");
} // .western-container

I would say, super helpful. You can go one step further and define multiple variables within a map.

$type: (action, #fc0), (western, #8a472c);

@each $movie, $color in $type {
    .#{$movie}-container {
        background-image: url("assets/images/#{$movie}-bg.jpg");
        color: $color;
    } // .#{$movie}-container
} // end @each

Which becomes:

.action-container {
    background-image: url("assets/images/action-bg.jpg");
    color: #fc0;
} // .action-container

.western-container {
    background-image: url("assets/images/western-bg.jpg");
    color: #8a472c;
} // .western-container

Using Sass maps is super helpful within loops. Check those out here.

@while

I rarely use @while loops. You can accomplish most everything you might need to achieve with @if or @each directives. That said, they are sometimes useful. Particularly within a @mixin since they run if a condition is met avoiding extra code.

$num: 4;

@while $num > 0 {
    .block-#{$num} {
        content: "#{$num}";
    } // .block-#{$num}
    
    // Reset loop and go again.
    $num: $num - 1;
} // end @while

This outputs:

.block-4 {
    content: "4";
} // .block-4

.block-3 {
    content: "3";
} // .block-3

.block-2 {
    content: "2";
} // .block-2

.block-1 {
    content: "1";
} // .block-1

Advanced Usage

Separately, any of these can be a major help, but you generate more markup to turn a @mixin into something like a function for Sass.

Here’s an example with documentation, which outputs a standard hamburger button.

//-----------------------------------------
// Make the Hamburger Icon
//-----------------------------------------
@mixin generate_hamburger($width, $height, $space, $color, $position, $radius, $speed) {    

  // Start variables.
  $gutter: $height + $space;
  
    // Determine position left right or center.
    @if $position == right {
        float: right;
    } @else if $position == left {
        float: left;
    } @else {
        margin-left: auto;
    margin-right: auto;
    }
    margin-bottom: $height + $space;
    margin-top: $height + $space;
    position: relative;
    text-indent: -9999em;
  
  // All bar sizes.
  &,
  &::before,
  &::after {
    background-color: $color;
    
    // Border radius?
    @if $radius != 0 {
      border-radius: $radius;
    }
    height: $height;
    transition: all $speed ease-in-out;
    width: $width;
  } // &, &::before, &::after
  
  // Top/bottom bars.
  &::before,
  &::after {
    content: "";
    left: 0;
    position: absolute;
  } // &::before, &::after
  
  // Top bar.
  &::before {
    top: -$gutter;
  } // &::before
  
  // Bottom bar.
  &::after {
    bottom: -$gutter;
  } // &::after
}

//-----------------------------------------
// Usage
//-----------------------------------------
.menu-toggle {
    @include generate_hamburger(30px, 5px, 5px, #000, null, 5px, 0.3s);
} // <div class="menu-toggle"></div>

You could take this even further to add a focus state with some animation doing like this. We’ll add a is-active class and some js to help us along.

//-----------------------------------------
// Make the Hamburger Icon
//-----------------------------------------
@mixin generate_hamburger($width, $height, $space, $color, $position, $radius, $speed) {    

  // Start variables.
  $gutter: $height + $space;
  
    // Determine position left right or center.
    @if $position == right {
        float: right;
    } @else if $position == left {
        float: left;
    } @else {
        margin-left: auto;
    margin-right: auto;
    }
    margin-bottom: $height + $space;
    margin-top: $height + $space;
    position: relative;
    text-indent: -9999em;
  
  // All bar sizes.
  &,
  &::before,
  &::after {
    background-color: $color;
    
    // Border radius?
    @if $radius != 0 {
      border-radius: $radius;
    }
    height: $height;
    transition: all $speed ease-in-out;
    width: $width;
  } // &, &::before, &::after
  
  // Top/bottom bars.
  &::before,
  &::after {
    content: "";
    left: 0;
    position: absolute;
  } // &::before, &::after
  
  // Top bar.
  &::before {
    top: -$gutter;
  } // &::before
  
  // Bottom bar.
  &::after {
    bottom: -$gutter;
  } // &::after
  
  // Active state.
  &.is-active{
    @include activate_hamburger(#675aac);
  } // &.is-active
}

// If active.
@mixin activate_hamburger($color) {

  // Top/bottom bars.
  &::before,
  &::after {
    background-color: $color;
  } // &::before, &::after

  // Top bar.
  &::before {
    top: -1px;
    transform: rotate(45deg);
  } // &::before

  // Bottom bar.
  &::after {
    bottom: 1px;
    transform: rotate(-45deg);
  } // &::after
}

//-----------------------------------------
// Usage
//-----------------------------------------
.menu-toggle {
    @include generate_hamburger(30px, 5px, 5px, #000, null, 5px, 0.3s);
} // <div class="menu-toggle"></div>

See the Pen Hamburger Mixins by jomurgel (@jomurgel) on CodePen.

Conclusion

Sometimes it’s the little things. With the goal to optimize load times, increase proficiency, and generate dynamic content easily, it’s a no-brainer that utilizing control directives in Sass is the way to go. At the very least, it can cut your dev time in half on certain tasks. I wholeheartedly recommend taking a deep dive into Sass and the power of if(), @if, @else, @else if, @for, @each, and @while.

We’d love to know how people use loops in new and exciting ways. Let us know in the comments below.

The post Get Loopy with Sass appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2017/02/07/get-loopy-sass/feed/ 0 16553
Brackets for WordPress: 2016 Edition https://webdevstudios.com/2016/07/26/brackets-for-wordpress-2016-edition/ https://webdevstudios.com/2016/07/26/brackets-for-wordpress-2016-edition/#comments Tue, 26 Jul 2016 17:24:15 +0000 https://webdevstudios.com/?p=13402 I have been an avid Brackets user since 2013. It’s a free, lightweight, open-source code editor that is perfect for beginners and experienced developers alike. One of my favorite features of Brackets is the number of extensions available to allow users to tailor their development experience. Today, I’ll share which extensions I use to make my job Read More Brackets for WordPress: 2016 Edition

The post Brackets for WordPress: 2016 Edition appeared first on WebDevStudios.

]]>
I have been an avid Brackets user since 2013. It’s a free, lightweight, open-source code editor that is perfect for beginners and experienced developers alike. One of my favorite features of Brackets is the number of extensions available to allow users to tailor their development experience. Today, I’ll share which extensions I use to make my job as a front-end WordPress developer easier.

User Experience

Color Preview

Brackets Color Preview extension

As the name suggests, this handy extension provides you with a preview of the colors you’re using in your files in the gutter of the file. I’ve found it can sometimes be a bit buggy if you’re using a Sass variable in partial, but the initial variable declarations work perfectly.

Brackets Icons

Brackets Icons gives a quick visual cue of the file types in your project. Choose between Devicons or Ionicons.

Brackets Icons
Brackets Icons with Devicons on the left, and Ionicons on the right.

Show Whitespace VS

By default, Brackets doesn’t give you any indication of indents or whitespace. Some may see this as a shortfall, but I love it because it means I get to choose how my tabs and spaces look. Show Whitespace VS displays whitespace the same way Visual Studio does (which I’ve never used!), and I like it because it’s simple and doesn’t get in the way of my code (plus, I can see all the whitespace).

Honorable mention: Indent Guides

Display Shortcuts

Brackets Display Shortcuts

After using Brackets for three years, I finally figured it was about time to learn some keyboard shortcuts. This extension is great because allows sorting and filtering, so you can focus on mastering keyboard shortcuts one extension at a time. And of course, it has a shortcut! Hit Control + Alt(Option) + /

Projects

This extension is particularly great if you’ve got the entire wp-content directory under version control because it gives you the ability to customize the name of your project. Hitting Opt + P on Mac brings up a project switcher to make it even easier to toggle between projects. ?

Front-End Development

Task Runners & Package Management

Brackets Bower

Terrified of the command line but want to use Bower to manage your front-end dependencies? No worries! Search the Bower directory, install your dependencies, and this extension will automatically add dependencies to your bower.json file, and you can easily manage where dependencies are installed by adding/editing the .bowerrc file.

Brackets Grunt

Brackets Grunt

Need to run a Grunt task but don’t want to leave your text editor? No problem, simply double click the task you want to run, and boom, you’re gold. The status side of the panel lets you know whether your task completed successfully, or failed with errors.

Honorable Mention: NodeJS Integration which allows you to run Gulp tasks.

Time Savers

WordPress Hint

This extension is a must for any WordPress developer. This adds hinting and autocompletion for WordPress theme and plugin development, and also includes hints for Woo Commerce development.

Brackets Git

Brackets Git

This is my absolute favorite, most-used Brackets extension. Even if you’re really comfortable using Git on the command line, this extension makes it really stupidly easy to follow the WDS motto: commit early and often. Changed files are added to the Git window, check the files to stage them, and click the commit button to commit. You can also fetch, pull, and push, and if you need it, there’s a shortcut to open the terminal.

Sass Hints

This extension adds autocompletion for Sass variables, and will save your sanity. No need to remember variable names, or search through files to figure them out. You can also see the value assigned to the variable to make sure you’re getting the right thing (which is also good for double-checking variables are only defined once!).

CSS Class Code Hint

This is really handy if you’re adding components to your site and want to utilize already-existing CSS classes.

Snippets (by edc)

I’m totally under-utilizing this extension, but it’s a necessity to help you save your sanity, and make your coding consistent. It’s especially useful for automating things like creating SCSS comment blocks, common WordPress function blocks, and CSS styles you find yourself reaching for constantly.

Align It!

Brackets Align It!

Say goodbye to hitting your spacebar repeatedly, and hello to Align It! With a simple keyboard command, align all your associative arrays and variable declarations.

Sort Text

We love [alphabetical] order at WDS, and Sort Text makes alphabetizing SCSS properties a breeze. Simply select your properties, hit Cmd + on Mac, and hey presto! you have alphabetized styles.

FuncDocr

Brackets FuncDocr

Typing /** or Ctrl + Shift + D on mac before an existing function will scan the function and scaffold a comment with placeholders for a description, parameters, and returned information. Simply tab through the options to document the function. FuncDocr works with both JavaScript and PHP.

Bonus

Kitten Cat Dog Gifs for Relaxation

Because sometimes you need a break from writing code to look at adorable, fluffy creatures.

This list only scratches the surface of super helpful extensions available for Brackets. If you’re interested in getting started with Brackets, check out Stacy’s ode to Brackets where she outlines a bunch of other useful features and extensions. I also keep a running list of extensions I’m using in a Gist, and am constantly looking for new extensions to improve my workflow.

The post Brackets for WordPress: 2016 Edition appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2016/07/26/brackets-for-wordpress-2016-edition/feed/ 7 13402
A Strategy for Styling Gravity Forms https://webdevstudios.com/2016/05/03/a-strategy-for-styling-gravity-forms/ https://webdevstudios.com/2016/05/03/a-strategy-for-styling-gravity-forms/#comments Tue, 03 May 2016 16:43:05 +0000 https://webdevstudios.com/?p=12700 Over the past few weeks, there has been a lot of work done to the starter theme we use at WDS, known as wd_s. Everything from incorporating a pattern library, migrating our build system from Grunt to Gulp, and adding some really great menu enhancements are just a few that we’ve covered! Another enhancement we wanted Read More A Strategy for Styling Gravity Forms

The post A Strategy for Styling Gravity Forms appeared first on WebDevStudios.

]]>
Over the past few weeks, there has been a lot of work done to the starter theme we use at WDS, known as wd_s. Everything from incorporating a pattern library, migrating our build system from Grunt to Gulp, and adding some really great menu enhancements are just a few that we’ve covered!

Another enhancement we wanted to make was to add a set of base styles directly into the theme for Gravity Forms. I decided to take this task on! Here’s the process I went through to make it happen:

Why a Base Set of Styles?

Applying custom styles to a Gravity Form can turn messy real quick. It can also be very time-consuming if you aren’t familiar with it, because you will be spending the majority of your time trying to figure out what selector to use.

NOTE: I will be referring to Gravity Forms as GF through this post.

Since we use GF on many of our projects, it only seemed logical to set up a simple, not-too-opinionated set of styles that provide a nice starting point for all new projects–something that would cover the most commonly used form fields and provide the ability for extending if necessary.

The Goal

I want this post to be helpful for anyone using Gravity Forms. I may refer to the wd_s theme specifically, but the ideas shared should apply under the context of any theme. I hope to save you time in your Gravity Form styling adventures by detailing a few of the problems I worked to overcome and provide some helpful tips and strategies along the way!

There are quite a few points I want to touch on in this post, so I won’t be focusing so much on the code, but the thinking behind why I went about things a certain way.

I will provide a direct link to the base style file at the end of the post. Please take the time to review it and use it!

Initial Requirements

As I was getting input from my co-workers and getting a game plan together, I put together a few requirements or goals for these base styles:

  • Styles should not require any configuration by user–an example of this would be a user having to add class names to fields when creating a form (other than CSS Ready classes).
  • Local GF variables should integrate into existing form variables but have the ability to be customized.
  • Avoid the use of !important –this tends to happen a lot when styling GF.
  • Account for common fields only–the advanced/complex fields can be addressed on a case-by-case basis.
  • Sass–keep nesting to a minimal.

Resources

The Gravity Forms documentation is pretty great, but there are two key pieces I thought were most helpful:

  • CSS Targeting Examples
    Referencing these examples will show you exactly what selectors you need to use to target a specific field type.
  • CSS Ready Classes
    These are classes provided by GF and are used mostly for creating more advanced form layouts such as a form that has two columns. Knowing these classes is important when you want to override the default styles. For example, we will be tweaking the .gf_left_column and .gf_right_column classes a bit later.

Sensible Local Variables

One of the awesome features of Sass is the ability to use variables. Using variables in form styles helps to provide consistency as well as the ability to quickly apply a set of changes!

I would advise against going crazy and creating all kinds of variables. Be deliberate and start out with a select few. You can always add to them later as the need arises.

Here are the variables I chose to target:

//--------------------------------------------------------------
// LOCAL VARIABLES
//-------------------------------------------------------------------

// Form
$gf-padding: 0; // set outer padding on form
$gf-bg: $color-white; // background color of form
$gf-border-width: 0; // border-width on form
$gf-border-color: $color-white; // border color

// Fields / Rows
$gf-field-margin-bottom: rem(25); // margin between field and label below (vertical spacing between rows)

// Labels
$gf-label-font-size: rem(16);
$gf-label-font-color: $color-mineshaft;
$gf-label-font-weight: 700;

// Inputs
$gf-input-color-background: $color-white;
$gf-input-color-border: $color-input-border;
$gf-input-color-text: $color-input-text;
$gf-input-color-focus-text: $color-input-focus-text;
$gf-input-padding: $padding-input;

As you can see, the input variable values are initially tied into the global form variables but can be overwritten if necessary.

Filling Parent Element

One of my biggest pet peeves about the default GF styles is that the main form wrapper does not fill its parent element. This is especially a problem on forms that are two-columns–and as we know, alignment with the rest of the content is paramount.

Here’s an example of what I mean:

form1

In short, the widths for the form wrapper, columns, and inputs needed to be adjusted in order to achieve the desired result which looks like this:

form2

BOOM! Notice how the form extends the full-width of the containing element and the form fields extend the full width of the form itself.

Strategies for Overcoming !important

If you have ever applied custom styles to a Gravity Form, you have undoubtedly had to use !important to override the GF default styles. Don’t worry, I’m right there with you!

In my first pass at coding these base styles, I resorted to using !important fourteen times. Yikes! This was not acceptable and I needed to find a better way to apply these styles that wouldn’t require so many uses of !important.

This is when being able to get input from awesome co-workers is invaluable!

Enter Damon

damon
Damon presented the idea of creating one content specific selector that could be used to house all of the styles that needed to override the GF defaults. The thinking behind this was to just target anything GF form related in this selector that needed higher specificity.

Here is an example of what I mean:

#content .gform_wrapper {
margin-right: 0; // allow for full width of containing element
	max-width: 100%; // allow for full width of containing element

	// Standard fields
	input[type="text"],
	input[type="url"],
	input[type="email"],
	input[type="tel"],
	input[type="number"],
	input[type="password"],
	input[type="file"],
	textarea{
		padding: $gf-input-padding;
		width: 100%;

		@include media($phone-landscape) {
			width: 49%;
		}
	}
}

Using the #content selector makes all selectors in this block more specific than the default GF styles which results in them taking higher priority. As long as the GF style isn’t using an !important, our styles will override!

This was a brilliant idea and allowed for getting rid of all but two uses of !important!

Mobile Styles

As I was working through this task, I quickly realized that just having some default mobile styles in place would be a huge time-saver. At WDS, we typically like our forms to have inputs that have a width of 100% on mobiles and then adjust accordingly as the screen-size grows.
mobile-form
Having these mobile styles built into the default wd_s theme styles is going to save us time and maybe one less headache!

Wrapping Up

In the end, taking on the task of writing these base GF styles was a great learning experience. It really drives home the point of we should always be trying to identify ways to improve our workflow and make ourselves more efficient.

I encourage you to go checkout the full code on Github. Please leave your questions, comments, or suggestions below! I want to hear from you.

The post A Strategy for Styling Gravity Forms appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2016/05/03/a-strategy-for-styling-gravity-forms/feed/ 9 12700
Using Sass Mixins to Power Your Projects https://webdevstudios.com/2016/03/01/using-sass-mixins-power-projects/ https://webdevstudios.com/2016/03/01/using-sass-mixins-power-projects/#respond Tue, 01 Mar 2016 17:34:25 +0000 http://webdevstudios.com/?p=12554 If you’ve followed along the WDS blog/Github/Twitter etc, you’ll know pretty well by now we’re a team that uses Sass as a part of our daily workflow for front-end styling. Sass is a powerful CSS preprocessor tool and it’s awesome. If you’re late to the game or new to front-end development there are lots of great Read More Using Sass Mixins to Power Your Projects

The post Using Sass Mixins to Power Your Projects appeared first on WebDevStudios.

]]>
If you’ve followed along the WDS blog/Github/Twitter etc, you’ll know pretty well by now we’re a team that uses Sass as a part of our daily workflow for front-end styling. Sass is a powerful CSS preprocessor tool and it’s awesome. If you’re late to the game or new to front-end development there are lots of great resources for getting started with Sass. 

Please note: This post will assume that you have at least a basic understanding of Sass and have used it at least a handful of times.

Today, we’ll be skipping over some of the basics like variables, nesting, and partials and get to some of the more intermediate working of Sass, specifically mixins, and we’ll touch on placeholders briefly as well. Mixins are a fantastic way to create and package blocks of reusable code so that you don’t have to continuously write out items that can become repetitive and sometime tedious (not to say they’re not important).

Before we completely dive into some cool mixins I’ve come across and libraries to checkout, I will quickly touch on placeholders vs. mixins. There’s been quite a bit of discussion around the web on the topic, but it’s a bit all over the place, so I wanted to cover some of what I found while doing some research for this post.

I think this first post by Hugo Giraudel speaks to front-end development work in general: “It depends.”

Hugo goes on to say:

The best advice would be: if you need variables, use a mixin. Otherwise, extend a placeholder. (placeholder vs mixin).

I think that’s solid advice and typically how I approach the topic as well. What’s also worth noting here is that Shay Howe did some pretty extensive research on the topic, the results of which I found as surprising as he did in his article, “Sass Mixins vs Extends the Data.”

It seems as though big picture, mixins create a bit more bloat in the compiled output and that they resulted in faster load time overall, which was interesting and seemed noteworthy as that’s an important detail not to be overlooked.

Despite that discovery, I still think both have their place and can be useful in certain projects. More or less, that puts us back to where we started–it depends on the project and situation, as always! With all front-end development, as long as it works, makes sense, and has been carefully thought through, there’s no reason not to use both in a given project from my perspective.

Here at WDS, we have several useful mixins included in our wd_s theme that are worth checking out. They’re particularly useful for our most common use cases. In this post, I will highlight some additional useful (less common) mixins that I’ve come across and used before. We haven’t necessarily included them in wd_s (at least not yet), because we intentionally keep things relatively lean there.

If you’re new to mixins, it would be wise to make sure you have a basic understanding. The following list is by no means comprehensive, but I tried to find a few that we’ve either used here at WDS or didn’t appear on every other list of “Top 10 Mixins that Should Be in Your Toolbox Post.” That’s not to say they won’t appear in other places–they are just not quite as common as breakpoint mixins or px to rem conversions.

Cross Browser Opacity Mixin

We all know cross browser compatibility is certainly improving with modern browsers, but even today, the struggle is real, and there are lots of projects that still require backwards compatibility for various reasons. This one should work all the way back to and including IE6.

@mixin opacity($opacity) {
    $opacity-ie: $opacity * 100;

    filter: alpha(opacity=$opacity-ie); //IE8
    opacity: $opacity;
}

//Usage
.faded-text {
    @include opacity(0.8);
}

Centering Mixin(including a new Fancier Version for Vertical/Horizontal/Both options)

Centering elements vertically, horizontally, or in some cases both axis, can always be a bit of a struggle for a variety of reasons. This mixin requires the parent element to have a position of relative to work and the mixin should be applied to the child element you’re trying to center vertically/horizontally or both. Here is the mixin–and be sure to check it out in its full glory on CSS-tricks.com.

@mixin center($horizontal: true, $vertical: true) {
    position: absolute;

    @if ($horizontal and $vertical) {
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    } @else if ($horizontal) {
        left: 50%;
        transform: translate(-50%, 0);
    } @else if ($vertical) {
        top: 50%;
        transform: translate(0, -50%);
    }
}

Font Stack Mixin

This is particularly useful for combining fonts and font weights. I find this one super useful for when you have to manage multiple fonts and weights throughout a project. It’s also super useful also if you are working in a multilingual project and certain languages require different fonts within the same project. Hat tip to Stacy Kvernmo, the original creator of this.

Title Border

This may not be an everyday use case mixin, but it was used on a recent project and came in pretty handy considering the number of times we had to implement a partial title border that didn’t need to be flexible depending on which section of the site or particular page a user might be visiting. This particular version has a number of arguments you can pass through which was a nice touch and well done. Hat tip to fellow teammate Allison Tarr on this one.

// Title Border
// Apply a short border beneath a title
// Usage @mixin title-border(color);

@mixin title-border($color, $height, $width, $position) {

    @if $position == center {
        $position: 0 auto;
    } @else {
        $position: 0;
    }

    &:after {
        border-bottom: $height solid $color;
        content: '';
        display: block;
        margin: $position;
        padding-bottom: rem(15);
        width: $width;
    }
}

//Use Case:

.h1 {
    @include title-border($color, rem(5), rem(85), left);
}

Sticky Footer:

While poking around on CodePen, I came across this sticky footer mixin by Zoe Rooney. I quite like this and could see some practical use cases for this being used as we begin (hopefully) the trend away from hamburger menu for navigation. As mobile phone use continues to grow each month for everyday web browsing, this seems like a very practical application.

Tooltips:

Although I will say I’m not a super huge fan of tooltips, there are some fairly good use cases for them from time to time throughout a project so long as they’re not abused. This tooltip mixin uses only HTML and CSS(SCSS), and is a nice combination of a few mixins to make this a well done reality.

These are just a few mixins and use cases for them. In addition to these, and the ones in our wd_s starter theme, there are a number of libraries worth looking into as well for mixins and may already be incorporated into your workflow, like Bourbon.io (part of wd_s).

Some noteworthy libraries to also check out. Full disclosure: I’ve not thoroughly gone through all of these but they look worthy of investigating further: 

Sass mixins are undoubtedly powerful and useful for building all types of sites. Do you have any mixins that you particularly like or use often that you’ve found helpful for your own projects? If so, feel free to share them in the comments! We’d love to hear from you!

The post Using Sass Mixins to Power Your Projects appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2016/03/01/using-sass-mixins-power-projects/feed/ 0 12554
Getting Sass-y with Color Functions https://webdevstudios.com/2016/02/16/sass-color-functions/ https://webdevstudios.com/2016/02/16/sass-color-functions/#respond Tue, 16 Feb 2016 17:20:17 +0000 http://webdevstudios.com/?p=12537 I love me some Sass. I also love the color purple, as you’ll discover below. I think part of the reason I dig SCSS is because you can dip your toes in gradually, which is less overwhelming. As time goes on, you get to continue to discover new things as you dive deeper (and brain Read More Getting Sass-y with Color Functions

The post Getting Sass-y with Color Functions appeared first on WebDevStudios.

]]>
I love me some Sass. I also love the color purple, as you’ll discover below. I think part of the reason I dig SCSS is because you can dip your toes in gradually, which is less overwhelming. As time goes on, you get to continue to discover new things as you dive deeper (and brain space allows).

Does my sassiness upset you? Why are you beset with gloom?” ~Maya Angelou

Don’t be gloomy; be Sass-y. Sass is powerful because it can increase your code efficiency and helps introduce more modular elements that can be incredibly helpful for using across larger projects.

Sass-y Colors

One thing you might already be aware of is the ability to create color variables (check out our starter theme wd_s for some examples of this). Creating variables is great to help differentiate hexadecimal codes (#DC143C) to something more palatable ($ruby-red-slippers). Let’s use those variables and ramp them up to help streamline other portions of your site!

Color functions combined with the ‘for’ control directive can lead to a magical world of loops. And as someone who works at a WordPress company, I am ALL ABOUT LOOPS.

The code above is an example of utilizing an existing color variable within a ‘for’ directive. Loosely translated into human-speak, it is saying for all elements ( $i ) from one to fourteen that have the class of ‘box’, increasingly darken the background color by a factor of three.

Grid of Purple SquaresDepending on your content, you’ll wind up with a gradient-type design going through your grid of boxes without having to sort out all the different hexadecimal codes.

Now, what if you want to create a consistent effect across your site for an element like a button? You can create a mixin using color functions to streamline it!

@mixin buttonColorProperties($color) {
    $border: adjust-hue($color, -6deg);
    background-color: $color; 
    border: 3px solid $border;
}

@mixin buttonColors($baseColor) {
    @include buttonColorProperties($baseColor);
  
    &:hover {
      $base-hover: darken($baseColor, 30);
      
      @include buttonColorProperties($base-hover);
      transition: all 0.25s;
    }
}

.button-purple  {
  @include buttonColors($violet-base);
}

The concept is to supply one base color and let the mixin take care of the other aspects you would like to define. In this case, the button is supplied the base color. From that variable, the hover effect and border are taken care of automatically.

What happens when you combine the first ‘for’ directive with the mixin? You get a lot of purple and a less-than-subtle button design but you also get a gradient of button backgrounds and an automatically implemented hover effect. Keep in mind that you can add other variables within your button design (maybe a highlight or a shadow?).

Go forth and be Sass-y. And if you create a cool button mixin*, be sure to share it with me!

*(Bonus points if it involves purple.)

The post Getting Sass-y with Color Functions appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2016/02/16/sass-color-functions/feed/ 0 12537
Using Sass to Manage Layers with z-index https://webdevstudios.com/2015/09/22/using-sass-to-manage-layers-z-index/ https://webdevstudios.com/2015/09/22/using-sass-to-manage-layers-z-index/#comments Tue, 22 Sep 2015 17:19:29 +0000 http://webdevstudios.com/?p=11680 On a recent project, I started to feel a bit overwhelmed with managing numerous layers with z-index. The thing about z-index is that all of the layers have to be in order, so I end up with multiple z-index declarations in multiple files all over the place. It’s also hard to keep track of the numbers; Read More Using Sass to Manage Layers with z-index

The post Using Sass to Manage Layers with z-index appeared first on WebDevStudios.

]]>
On a recent project, I started to feel a bit overwhelmed with managing numerous layers with z-index. The thing about z-index is that all of the layers have to be in order, so I end up with multiple z-index declarations in multiple files all over the place. It’s also hard to keep track of the numbers; bump one up and you have to go bump all the others up as well. It gets a bit tedious, especially when you have numerous layers. This can all be fixed with a little bit of Sass, and here’s how to do it!

$layers: (
    'navigation', // z-index: 0
    'logo', // z-index: 2
    'login-popup', // z-index: 3
    'overlay', // z-index: 4
);

@function layer-index($layer) {
    // This just returns the named layer's 
    // location in the list, which becomes it's z-index.
    @return index($layers, $layer); 
}

@mixin z-index($layer, $position:relative) {
    position: $position; // relative by default
    
     // Set the z-index to the named layer's index in the list.
    z-index: layer-index($layer);
}

.navigation {
    // Use this to name your layers and position them.
    @include z-index(navigation, absolute); 
}

.logo {
    @include z-index(logo); // Relative by default
}

.login-popup {
    @include z-index(login-popup, absolute); 
}

.overlay {
    @include z-index(overlay, absolute);
}

Just use @include z-index(your-name-goes-here, absolute); to name your layers, and specify its position. Then, add the name to the list of layers in $layers at specific positions in the list (top most layers go towards the bottom). The order of the $layers list is what does the trick. If we wanted the logo to show over the overlay, for instance, we would just move 'logo', right below 'overlay', to get the effect.

All you have to do now is make sure all your elements with z-index use the @include z-index() mixin to name the layer and add it to a position in the $layers list.

An Example

Here we have two menus on a mobile layout. On a mobile layout they are going to overlap a bit, especially if they use both menus at the same time. Right now, the secondary navigation is not accessible; we need to bump that layer up.

Two menus where the second one is inaccessible because of z-index
What we’re starting off with–an inaccessible secondary navigation.

 

Let me show you what we need to do get those two layers squared away with ease:

Naming the secondary navigation layer.
Name the tools navigation menu.
Naming the Main Navigation
Name the main navigation.
Adding the Layers
Add the named layers to the list.
Switching the layers using Livereload
Here’s some live reload action on how easy it is to change our layers now.

Now your days of complicated layer management is over. No numbers to keep track of–just layers you can order easily!

The post Using Sass to Manage Layers with z-index appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2015/09/22/using-sass-to-manage-layers-z-index/feed/ 5 11680
Create Simple Inline Media Queries with include-media https://webdevstudios.com/2015/05/18/create-simple-inline-media-queries-include-media/ https://webdevstudios.com/2015/05/18/create-simple-inline-media-queries-include-media/#respond Mon, 18 May 2015 17:04:13 +0000 http://webdevstudios.com/?p=11231 Lately, I’ve been thinking that our current method of using inline media queries throughout our Sass partials has not been flexible enough for the projects we’ve been building. While it was simple and allowed for easy implementation, I think it is time to try yet another Sass library–specifically include-media. Eduardo Bouças, developer of include-media, states Read More Create Simple Inline Media Queries with include-media

The post Create Simple Inline Media Queries with include-media appeared first on WebDevStudios.

]]>
Lately, I’ve been thinking that our current method of using inline media queries throughout our Sass partials has not been flexible enough for the projects we’ve been building. While it was simple and allowed for easy implementation, I think it is time to try yet another Sass library–specifically include-media.

Eduardo Bouças, developer of include-media, states on the website:

“include-media is a Sass library for writing CSS media queries in an easy and maintainable way, using a natural and simplistic syntax.”

Simple, Natural Syntax

While there are many libraries out there to choose from, I really enjoy the syntax used by include-media. When writing code, it is always helpful to be able to translate what you are writing to your native language (in your head, of course).

Operators, FTW

I love using the operators as it is so simple to see what is taking place. Many media query libraries do not take into account the max value of the smaller breakpoint and the minimum value of the larger one, which means both media queries will be active at that same time potentially causing conflict. Having the ability to use the >= (greater than or equal to) or <= (less than or equal to) is very exciting.

BYOB

Bring your own Breakpoint names and values! By default, include-media will help you get started with the following:

$breakpoints: (
    phone: 320px,
    tablet: 768px,
    desktop: 1024px
);

I recommend that you redeclare these breakpoints based on when your content actually needs a breakpoint. You can also use your own naming conventions as well if device name is not your thing. To redefine your breakpoints, use the same Sass Map syntax. include-media can accept px, em or rem units:

$breakpoints: (
    phone: 24em,
    tablet: 50em,
    desktop: 72em
);

Now let’s put these babies to use:

.primary {
     // look at me, I’m mobile first and full width
    width: 100%;    

    // then when I reach a point where my main content area may be too wide
    // we can now call in our breakpoint
    @include media(">phone", "<=tablet") {
        width: 35%;
    }
}

How simple is that? I love speakable code.

Custom Values

Do you need an on-the-go breakpoint for those one-off situations? I am in favor of making variables for as many values as possible, but if that is your style this is for you:

@include media(">desktop", "<=2600px") {
    content: 'Why is your browser so wide?';
}

Supports Media Types and Static Expressions

You can target media types screen, print, handheld the same way you’d target a size:

.primary {
    content: 'screens are awesome';

    @include media("print") {
        content: 'people print websites?';
    }
} 

Or target retina screens:

.primary {
    // I’m a regular sized logo
    background-image: url(images/logo.png);

    // I’m a SUPER logo for pretty retina screens
    @include media("retina2x") { 
        background-image: url(images/logo@2x.png);    
    }
}

Couple of Caveats

  • include-media may not work as expected if you are using other libraries that have a mixin named ‘media’, like Bourbon Neat.
  • I really would love the ability to target height as well and that may be a feature that is currently being developed.

Give it a Try

To get started, you can either download the single scss file and @import it to your project manually or you can install via Bower:

bower install include-media

and import dist/_include-media.scss into your project.

Further Reading

The post Create Simple Inline Media Queries with include-media appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2015/05/18/create-simple-inline-media-queries-include-media/feed/ 0 11231
Getting Started with SassDoc https://webdevstudios.com/2015/03/17/getting-started-with-sassdoc/ https://webdevstudios.com/2015/03/17/getting-started-with-sassdoc/#respond Tue, 17 Mar 2015 15:00:12 +0000 http://webdevstudios.com/?p=10728 SassDoc is to Sass what JSDoc is to JavaScript: a documentation system to build pretty and powerful docs in the blink of an eye. – SassDoc.com So your team is using Sass, and everybody is whipping out amazing @mixins, @extends, custom functions, and maximizing use of all those wonderful, built-in Control Directives (@if, @for, @each, Read More Getting Started with SassDoc

The post Getting Started with SassDoc appeared first on WebDevStudios.

]]>

SassDoc is to Sass what JSDoc is to JavaScript: a documentation system to build pretty and powerful docs in the blink of an eye.
SassDoc.com

So your team is using Sass, and everybody is whipping out amazing @mixins, @extends, custom functions, and maximizing use of all those wonderful, built-in Control Directives (@if, @for, @each, @while). Your team has a system in place for introducing new @mixins to other team members so everybody leverages the goodies. While each team understands each project’s Sass nuances and intricacies, there can be gaps in understanding for team members that are added, or even newly hired employees. This is where the often dreaded documentation can come in handy.

Projects like thoughbot’s Bourbon and Bourbon Neat generate and run their documentation site’s on SassDoc.

man hits something with hammer and shocked by explosion

Install SassDoc

These instructions assume you’re running Grunt, but SassDoc has documentation on other task runners, like Gulp. You could also just install SassDoc globally as a Node package, with:

# Install SassDoc globally
npm install sassdoc -g

And here is how I would do it (again, with Grunt):

npm install --save-dev grunt-sassdoc

Once the plugin is installed in your desired project be sure to add it to your Gruntfile.js.

grunt.loadNpmTasks('grunt-sassdoc');

And you can now run SassDoc with:

grunt sassdoc

Here is an example of a simple configuration for your Gruntfile, but there are plenty of other options to choose from:

// Tip: you're not required to pass every options,
// just set the one you need.
grunt.initConfig({
  sassdoc: {
    default: {
      src: 'path/to/source',
      options: {
        dest: 'path/to/docs',
        display: {
          access: ['public', 'private'],
          alias: true,
          watermark: true,
        }
      },
    },
  },
});

Writing SassDoc Compliant Comments

With SassDoc installed, we’re ready to start writing our Sass documentation and generating our custom site. Here is an example of some SassDoc compliant comments I wrote on a simple mixin:

// ----------------------------------------------------------------------

  // Margin auto

// ----------------------------------------------------------------------

////
/// @author Damon Cook
/// @group wds
////

/// Horizontally center a block element
///
/// @example scss - Basic Usage Sass
///    .center-my-block-thingie {
///        @include margin-auto();
///    }
///
/// @example scss - Basic Usage CSS Output
///    .center-my-block-thingie {
///        margin-left: auto;
///        margin-right: auto;
///    }

@mixin margin-auto {
    margin-left: auto;
    margin-right: auto;
}

Mostly it is just a matter of using three forward slashes to denote your SassDoc comment block, e.g. ///. Next, you’ll want to brush up on all the Annotations SassDoc has available: http://sassdoc.com/annotations/

#proTip: Use @group to Organize Your Entries

Since we include and use Bourbon Neat in our wd_s project starter via Bower, it is possible to generate and output Neat’s already included SassDoc comments in your project’s SassDoc site. Here is what I used in my Gruntfile on a recent project:

sassdoc: {
    default: {
        src: [
            'themes/custom-theme/sass/**/*.scss',
            'bower_components/bourbon/app/assets/stylesheets',
            'bower_components/neat/app/assets/stylesheets'
        ],
        options: {
            dest: './sassdoc/',
            display: {
                access: ['public'],
                watermark: false
            },
            groups: {
                wds: 'WebDevStudios',
                'undefined': 'Bourbon & Neat'
            },
        },
    },
}, 

Then I use the @group annotation to denote internal documentation vs Bourbon’s, like so:

/// @group wds

Which then outputs our SassDoc site to organize entries like so:
example SassDoc website output entry navigation

It is a bit of a workaround, and I would prefer that Bourbon’s maintainers included an @group bourbon in their SassDoc comments, but for now this works.

SassDoc Themes, and beyond

By default SassDoc comes with a handy theme, but also provides documentation on creating your own.

Hopefully, you’ve considered implementing some Sass documentation in your next project, and now have the tools to do so. Writing the documentation can add some additional overhead, but encourages consistency and increase knowledge sharing within teams.

Also, stay tuned–I’ll be updating this post in coming weeks as we roll out integration of SassDocs into our wd_s starter project.

The post Getting Started with SassDoc appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2015/03/17/getting-started-with-sassdoc/feed/ 0 10728
Mapping Icon Fonts with Sass https://webdevstudios.com/2015/01/28/mapping-icon-fonts-with-sass/ https://webdevstudios.com/2015/01/28/mapping-icon-fonts-with-sass/#comments Wed, 28 Jan 2015 13:30:51 +0000 http://webdevstudios.com/?p=10449 I love Sass, and I love using icon fonts. However, I do not like the limitations of using inline non-semantic, presentational markup to place these wonderful symbols, e.g. What if we could keep the embellishments in our stylesheet, minimize the HTML markup, and keep things a bit more semantic? I think we can, and this Read More Mapping Icon Fonts with Sass

The post Mapping Icon Fonts with Sass appeared first on WebDevStudios.

]]>
I love Sass, and I love using icon fonts.

However, I do not like the limitations of using inline non-semantic, presentational markup to place these wonderful symbols, e.g.

<i class="fa fa-trash-o"></i>

What if we could keep the embellishments in our stylesheet, minimize the HTML markup, and keep things a bit more semantic?

I think we can, and this is what we’ll accomplish in a few steps. I first came across this approach from Jayden Seric’s post, Fun With Sass & Font Icons.

We’ll be using the Font Awesome icon library for this example. Font Awesome offers a comprehensive library of icons, and they’re all free and GPL compatible.

Set a Sass variable for font-family of icon font

Let’s say we want to set up a social nav, and a Search bar icon as featured on our site.
Screenshot of WDS social nav and search

We’ll assume we already have Font Awesome enqueued properly in our WordPress theme (see wd_s for example). First, let’s declare our Font Awesome font-family as a Sass variable:

$font-icon: "FontAwesome";

Sass @mixin for icon fonts

We can use our newly defined $font-icon variable (line 18 below) within our new handy mixin to Kiss It Simple, Stupid (K.I.S.S.):

// For adding font icons to elements using CSS pseudo-elements
// http://jaydenseric.com/blog/fun-with-sass-and-font-icons
@mixin icon($position: before, $icon: false, $styles: true) {
    @if $position == both {
        $position: 'before, &:after';
    }
    // Either a :before or :after pseudo-element, or both, defaulting to :before
    &:#{$position} {
        @if $icon {
            // A particular icon has been specified
            content: "#{map-get($icons, $icon)}";
        }
        @if $styles {
            // Supportive icon styles required
            speak: none;
            font-style: normal;
            font-weight: normal;
            font-family: $font-icon;
        }
        // Include any extra rules supplied for the pseudo-element
        @content;
    }
}

Map Unicode Characters to Custom Aliases

Now here is where it gets interesting, because typically Font Awesome gives us icon classes with unicode characters, like:

  • .fa-search / Unicode: f002
  • .fa-facebook / Unicode: f09a
  • .fa-twitter / Unicode: f099
  • and so on

But now we can create our own mapping, and use any semantic, or non-semantic aliases:

// Map icon names to font unicode characters
$icons: (
    search: "\f002",
    facebook: "\f09a",
    twitter: "\f099",

    // or goofy aliases, like
    magnifying-doohickey: "\f002"
);

And now we use our mixin to assign our custom magnifying-doohickey icon to our Search, like so:

[href^="#search-popup"] {
    @include icon(before, magnifying-doohickey) {
        color: #b4b4b6;
        font-size: 24px;
    }
}

At first, this may seem like a bit of extra overhead because you’re having to manage the font mapping. However, this opens up the ability to mix-and-match your own custom SVG icons with existing libraries, like Font Awesome. Tools like Font Custom can auto-magically generate the icon mapping for you.

How often do we see icons that do not align with their contextual information, like the bullhorn icon sitting next to “Contact” in a main navigation?
screenshot of icon navigation

Now we can map an alias so in our project we can use @include icon(before, contact); instead of @include icon(before, bullhorn);, or better yet put it all in an @each loop

$icons: (
    // Font Awesome's .fa-user
    about: "\f007",
    // Font Awesome's .fa-bullhorn
    contact: "\f0a1",
    // Font Awesome's .fa-newspaper-o
    news: "\f1ea",
);
@each $nav-item in about, news, contact {
    & > li.#{$nav-item} > a {
        @include icon(before, #{$nav-item});
    }
}

I find this easier to manage in the long run, and hope you find it useful!

Further Reading

The post Mapping Icon Fonts with Sass appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2015/01/28/mapping-icon-fonts-with-sass/feed/ 2 10449