Skip to main content

Mobomo webinars-now on demand! | learn more.

Whether you're new to css layouts or a ninja css warrior we both share one common enemy: The Box Model.

The box-model is the way we calculate the width and height of an object. The W3C modal calculates the width and height by adding the padding and border to the width you specify ( width + padding + border / height + padding + border ). This is a pain because when we want to specify a width to be 400px wide, we first need to subtract the difference of the padding and border to make a 400px wide box. If we had a border of 10px and a padding of 20px, the width would be 340px wide (400 - 20 - 40 = 340px).

IE6 has a quirk where its box model calculated the width with the border and padding inside. When I started out as a developer I thought this was odd as other browsers calculated differently. This is how the border-box calculates the width. This really comes in handy when used for responsive design and fluid grids!

Box-sizing does take two values. First, the border-box as we have described above where the padding and border are inside. The second value, which is commonly used across browsers is content-box specified by CSS2. The padding and border are included to the width and height.

box-size comparison

Using box-sizing you can have fluid grids and keep all your gutters and borders inside. This makes it easier when starting out with responsive web design. We have begun using the border-box value for the box-size property in our recent Github pages (Omni Auth, Green Onion, Grape). Take a look at them as examples of how simple designs can be responsive with box-sizing: border-box property.

You can also play with sample code at Codepen.io.

Browser Support

  • Firefox 1-3, un-prefixed in current version
  • Safari 3, un-prefixed in current version
  • IE8+

code

  * {   -moz-box-sizing: border-box;   -webkit-box-sizing: border-box;   box-sizing: border-box;   }

By using the * you make all elements on the page use the box-sizing property.

If you have not started using box-sizing, I highly recomend using it in your projects. For the vetrans that know the old box modal this will help you with responsive web design. As mobile takes over, responsive design will become common practice, and the box-sizing property will become your new best friend!

Categories
Author

Here is a quick tip for users who like the idea of using SASS-powered stylesheets, but may not want to bother setting up a development framework to do so.

A Really Quick Intro to SASS

If you’re not familiar, SASS (“semantically awesome stylesheets”) builds off your existing CSS knowledge, but tosses some dynamic spice into the mix. The result leaves you with increased power and flexibility as a coder/designer.

The result is code that is easier to read, takes up less space, and supports the very helpful nesting of styling rules. Another tremendously useful feature is the ability to use variables throughout all of your stylesheets — something that becomes invaluable when working on larger websites or applications. SASS also supports mixins, operations, and beyond — learn more at the SASS website, or by reading Michael Bleigh’s excellent SASS intro.

SASS with static websites, you say?

Until somewhat recently, I’d only used SASS when jumping in to help with design work on pre-existing, larger Rails applications. This works great, as the markup is already in place and changes are easy to make. My SASS experience in this regard has been a good one.

When coding a new, larger site from scratch, however, I’ve never found a satisfying approach to use SASS from square one. I’ve dabbled with a few different SASS-compatible static website frameworks (Middleman, StaticMatic, etc) — but never felt comfortable enough with these to full integrate them into the beginning of my HTML/CSS coding process. As such, my preference has remained: build the layout in static HTML, and when fully coded & styled, integrate into the Rails app. Sadly, SASS fell by the wayside too often with this approach.

But finally, thanks to the latest beta versions of the HAML/SASS gem, an accessible solution lies in wait. This setup will auto-compile your SASS into CSS whenever changes are made. Best of all, no additional framework setup or files are needed… just what I’ve been looking for. Make it happen as follows:

1. Install the latest HAML/SASS gem

When I discovered this technique, the latest gem was installed as follows:

gem install haml-edge

However, in the meantime there have been beta releases of SASS 3.0, which should achieve the same ends. install this gem as follows:

gem install haml --pre

If you’re curious if anything more recent has been released, check out the HAML/SASS blog.

2. Setup your local project directory

Do this however you like: I usually start with an index.html and fresh directories for stylesheets, images, and javascript. Populate with any templates/frameworks you may have, as desired. Just make sure you have a directory for you SASS files in place. Here is an absolute bare-bones version to show how this technique applies:

3. Summon the sass --watch kraken

Finally, from the command line, run this line to make the magic happen:

sass --watch path_to_sass:path_to_css

The path before the colon is wherever your SASS files are located… the path after the colon is where you want the CSS to be generated. Of course, your HTML should reference the location of the CSS files. Keep in mind: when styling this way, any changes you make to a CSS file will be lost if/when the SASS file is changed (the overwrite is automatic).

Also note that you will need to run this step each time you want to enable auto-compiling SASS. It will run in the background, and instantly take action if a SASS file has been changed.

And that’s it. Whenever you make changes to any SASS files in the directory you specified, the corresponding CSS files will be automatically updated (and created, if necessary). This lets you benefit from the dynamic nature of SASS without requiring any framework setup.

Categories
Author

I am a huge fan of SASS (Syntactically Awesome Stylesheets) for styling Rails applications. I have been using it on all of my projects for quite a while now and have developed some great techniques that make it much easier to organize, write, and read stylesheets in an application.

Unlike HAML, SASS retains most of the same “feel” when writing the code as vanilla CSS. It simply adds more power and better organizational tools, making it an easy choice as a go-to replacement. You can teach someone the basics of SASS in about 30 seconds: use two spaces to indent everything, put the colon before the declaration and no semicolon afterwards. In fact, I’ve even written regular expressions to convert CSS to SASS mechanically in some cases. It’s easy to pick up and once you do you will start reaping real benefits.

The 20-Second “Get Up And Running”

To use SASS, you must have the HAML gem installed on your Rails app. Add it to your environment.rb:

config.gem 'haml', :version => '>= 2.0.6'

Now you can create SASS stylesheets simply by making .sass files in a public/stylesheets/sass directory.

Basic Example: Building a Menu the SASS Way

The best way to start explaining the power of SASS may be through one of the more common styling tasks one encounters: styling a menu. Here we’ll assume a menu structure like this:

<ul id='menu'>   <li><a href='/'>Home</a></li>   <li><a href='/about'>About</a></li>   <li><a href='/services'>Services</a></li>   <li><a href='/contact'>Contact</a></li> </ul>

To style this menu in CSS, we might do something like this:

#menu {   margin: 0;   list-style: none; }  #menu li {   float: left; }  #menu li a {   display: block;   float: left;   padding: 4px 8px;   text-decoration: none;   background: #2277aa;   color: white; }

SASS allows you to use indentation to indicate hierarchy, saving much repetition and space. The same code in SASS looks like this:

!menu_bg = #2277aa    #menu   :margin 0   :list-style none   li     :float left     a       :display block       :float left       :padding 4px 8px       :text-decoration none       :color white       :background = !menu_bg

Hierarchical selectors mean that if you indent something, the selector it falls under will automatically be prepended to it, so the two examples above generate the same output. You’ll also notice !menu_bg in the SASS code. SASS allows you to declare constants that can be reused throughout the code, a very useful feature when dealing with colors.

Now we have our basic setup for the menu, but let’s handle some better cases. I want the color to change when I hover over the menu options and I want to highlight the current menu option (we’ll assume that the <li> encapsulating the current menu item will have class ‘current’ when it is selected). Let’s add these features first using CSS, then SASS. With CSS:

#menu {   margin: 0;   list-style: none; }  #menu li {   float: left; }  #menu li a {   display: block;   float: left;   padding: 4px 8px;   text-decoration: none;   background: #2277aa;   color: white; }  #menu li a:hover {   background: #116699; }  /* Make sure the color doesn't change when the current option is hovered. */ #menu li.current a, #menu li.current a:hover {   background: white;   color: black; }

This isn’t too bad, but our selectors keep getting longer and longer. Let’s look at the same thing in SASS.

#menu   :margin 0   :list-style none   li     :float left     a       :display block       :float left       :padding 4px 8px       :text-decoration none       :color white       :background = !menu_bg       &:hover         :background = !menu_bg - #111111     &.current       a, a:hover         :background white         :color black

The ampersand (&) in SASS is a shortcut to insert the entire parent selector at that point. By using &.current I am saying “the parent selector with a class of current.” &:hover means “the parent selector when hovered.” This makes it easy to write complex selectors in a compact, easy-to-read manner.

Another great thing about SASS is it has built in CSS color math. Note where I declared :background = !menu_bg - #111111. That is equivalent to subtracting 1 from each of the values of the constant’s color, which in this case yields #116699. This is great, because now I can change the color of the menu and the hover state will automatically change without me having to manually find it and recalculate it for a new color. Note that whenever you are using constants or performing calculations you need to add the equals sign to your declaration.

Getting organized with a master.sass

Another way you can use SASS is to organize all of your CSS into a single file without having to worry about it in your view. I have recently started using this approach for a number of reasons:

  1. It allows me to control stylesheet inclusion from within the stylesheets themselves, making the structure more readable.
  2. I can define global colors that can then be used in any of the child stylesheets.
  3. It’s really easy!

In a new project, I always create a master.sass that will look something like this:

// Define app-specific colors first !green = #191 !gray = #555  // Now define globally applicable, general styles  body   :font-family Arial, sans-serif    a   :color = !green   :text-decoration none   :font-weight bold  // Now import all of your other SASS files, they will be // automatically included in the same generated CSS file // at compile time.  @import menu.sass @import content.sass @import admin.sass @import users.sass

Using this structure I have a modular, easily expandable collection of stylesheets with global color constants and basic styles. In addition, I can add this to my Rails application with the simplest of calls:

<%= stylesheet_link_tag 'master' %>

Wrapping Up

Hopefully this gives you a taste of the easy awesomeness that is possible with SASS. The greatest thing about the library is you don’t lose touch with writing CSS because SASS is CSS, just with a few extras and shortcuts to make power-styling easier.

Update: A commenter pointed out that I forgot the @ before my import statements in the master.sass example, this has been fixed.

Categories
Author

The discussion around HTML 5 has been heating up recently, with people advocating to get it finalized and implemented sooner rather than later (and lamenting the ulterior motives of major browser vendors in lobbying for specs). I simply can’t get passionate about this fight, much as I’ve tried. While some of the things that HTML 5 offers will certainly be a boon for web developers, by and large the issues that it addresses (in terms of interactivity) are surmountable simply by using the excellent Javascript libraries we’ve all become dependent upon. The next version of the CSS specification, however, is an entirely different story.

I recently started a new project and as an experiment decided to play with using the non-final border-radius implementations available in Firefox and Safari. After using it for about 15 minutes, I decided that I would simply forgo rounded corners in the interface for Internet Explorer. After using it for three days, I am wondering why every designer and developer on the internet isn’t simultaneously demanding immediate forced adoption of CSS3.

Styling is Fun Again

Our interfaces and style tastes have grown much more complex as the web has grown up, but the tools we use to implement those styles haven’t been keeping up. It shouldn’t feel like a trip to the dentist just to get a box to have some rounded edges. It shouldn’t be a nightmare to try to use translucent pngs for overlays (admittedly this has nothing to do with CSS3 and everything to do with IE6, the browser that won’t die no matter how much we pray).

I can tell you that styling on the edge doesn’t just feel good, it feels amazing. I’m able to implement in a few seconds what I might otherwise spend three hours styling while polluting my markup with hack tags.

Rounded Corners: Nemesis of Designers Everywhere

There is no good way to make rounded corners. The javascript libraries are buggy, images are limited in practicality, and getting it just right in all browsers is downright painful and usually ends up with markup something like this (and a whole mess of CSS to go with):

<div class='rounded'>   <div class='tl'>     <div class='tr'>       <div class='bl'>         <div class='br'>           So much for semantics...         </div>       </div>     </div>   </div> </div>

In the CSS3 specification, the same effect is achievable like so:

.rounded { border-radius: 10px; }

But it’s not just a convenient way to shortcut the hacks to which we’ve all grown accustomed, it opens up entirely new possibilities for design that would simply not be worth the effort to hack without it.

Lead By Example

Let me explain what I mean by example. Form design has always been one of the trickiest parts of web design, what can we do with a little CSS 3 magic? Let’s say we have a simple form that takes a person’s name:

<form id='sample_form'>   <label for="name">First Name:</label>   <input type='text' name="name" id="name"/><br/>      <label for="name">Last Name:</label>   <input type='text' name="name" id="name"/><br/>      <button type="submit">Submit</button> </form>

Simple enough, this turns out looking something like this:

Now we can add some standard CSS to make it look a little more acceptable:

label {   display: block;   float: left;   width: 100px;   font-weight: bold;   padding: 4px 5px;   font-family: Verdana, sans-serif;   font-size: 12px;   margin-bottom: 5px;   clear: both;   text-align: right; }  input {   font-size: 12px;   margin-bottom: 5px; } button {   margin-left: 115px;   margin-top: 10px; }

And our result is a perfectly usable form:

But what if we use just a taste of what CSS3 has to offer? We can make a form that looks completely unique without using a single image:

label {   display: block;   float: left;   width: 100px;   padding: 4px 5px;   border: 2px solid #037;   background: #06a;   color: #fff;   font-family: Verdana, sans-serif;    font-size: 12px;   margin-bottom: 5px;   font-weight: bold;   clear: both;   text-align: right;   border-radius: 13px;   border-top-right-radius: 0px;   border-bottom-right-radius: 0px; }  input {   background: #fff;   border: 2px solid #8ac;   border-left: 0px;   padding: 5px 5px;   margin-top: 0;   margin-bottom: 5px;   margin-left: 0;   border-radius: 5px;   top-left-radius: 0px;   border-bottom-left-radius: 0px; }  button {   background: #080;   color: #fff;   border: 2px solid #060;   font-size: 12px;   font-weight: bold;   margin-left: 112px;   padding: 5px 10px;   border-radius: 13px; }

It’s a hefty chunk of code, but anyone experienced in writing CSS can knock something like that out in about five minutes. The result is well worth it:

This kind of styling opens up with the application of just a single new attribute from the CSS3 draft specifications. Designers have had to hack, cheat, and wrangle every semi-complex interface that has been developed in the last 5 years thanks to the limitations of CSS (and more specifically the limitations of Internet Explorer), but it doesn’t have to stay that way forever.

State of the Browser

The complete CSS3 spec is not coming to a browser near you any time soon (more accurately not all browsers), and that’s a real shame. It brings to the table powerful new tools that can really enable the kind of semantic markup that we all wish was possible with today’s browsers. Rounded corners are just the “tip of the iceberg”; once CSS3 sees widespread adoption, interface design will take a leap forward unlike any it has seen before.

In the meantime, keep an eye out on the WebKit Nightlies for cutting edge CSS implementations (just added: CSS Variables). Five years from now we’ll look at the troubles we used to have and laugh. Until then, a person can dream…

Categories
Author

Browser compatibility, the web designer’s nightmare, has always seemed more difficult than it has to be. Why hasn’t there been an industry-standard, simple way to target CSS to specific browsers, allowing one to style the page properly without worrying about hacks and other difficult ways of pulling all the information together? I thought that something should be done about it, so taking Richard Livsey’s ‘browser_detect’ plugin as a starting point, I developed an automatic solution for including browser-specific stylesheets.

Browserized Styles provides a dead simple way to create browser-specific CSS code for
use in a Rails application. All you need to do is create a .css file targeted to
a browser by appending an underscore and identifier to the end.

Installation

 script/plugin install http://svn.intridea.com/svn/public/browserized_styles 

Example

Let’s say I have some complex CSS code that looks bad in some browsers, but works in
others. Let’s also say that i’ve put it into a stylesheet in stylesheets/complex.css.

My stylesheet link tag looks something like this:

 <%= stylesheet_link_tag 'complex' %>

Now all I have to do to target a browser is create a new CSS file with the browser’s
identifier appended to it with an underscore (e.g. “complex_ie6.css”). That’s it!
The same exact stylesheet link tag will automatically check the current user
agent and load a browser-specific CSS file if it exists. Ta-da! One-step browser
styles!

More information is available in the readme, but the end result is browser-targeting bliss.

The plugin is brand new and will probably see some modifications in the future. If you run into any problems or come up with a patch, feel free to submit it to the Intridea Public Trac .

Categories
Author

As much as we all strive to write perfect, semantic XHTML that can be styled entirely independently, the reality of browser compatibility and even our own creative choices often leads to design refactoring. Obviously in Rails one big help for this is the use of partials, making sure that you can change your markup in one place and it will be reflected for often-repeated content. But what about for lower-level, underlying layout structure? Nested partials quickly become a mess to deal with, and traditional helpers don't always offer the flexibility and intelligence that is needed to get the job done.

Enter block-accepting helpers. These allow you to wrap markup around content without the ugliness of a my_thing_start and my_thing_end. With a little more work, they can also provide an intelligent layout structure that requires minimal (and beautiful) code in the view. Let's start with a simple example. Lets say that most, but not all, of the pages in my app have a similar container and title. Creating multiple layouts using partials for everything just to add or not add a couple of lines of code is way too heavy. On the other hand, my designers want the flexibility to change how the container is represented in markup, so I can't just throw the markup into each action. Here's the markup I want (for now):

<div class='main_container'>      <h3><!-- Some Title --></h3>      <!-- Some Contents-->  </div>

This is obviously pretty basic, and wouldn't be a big deal to change if the design changed, but this is just an example. If you're dealing with some kind of nested div rounded corner solution, or any number of other necessary CSS/markup hacks to get the look you desire, it could become quite a chore. So how do we create our DRY helper? Primarily through the use of the concat method in the ActionView::Helpers::TextHelper module. Here's my helper (just put this in either the relevant helper or ApplicationHelper:

def main_container(options = {}, &block)    concat("<div class='main_container'>",block.binding)    concat("<h3>#{options[:title]}</h3>",block.binding) unless options[:title].blank?    yield    concat("</div>",block.binding)  end

So that wasn't so bad, was it? Now in our views all we have to do to get our main_container is:

<% main_container :title => 'My Page Title' do %>      <p>We can put whatever we want here, and it will appear inside the container.</p>  <% end %>

Cool, huh? There are other resources that dig much deeper into blocks, procs, and the ruby wonderfulness going on behind the scenes, but this is purely a functional demonstration. Suffice to say that placing a &block (or &proc or whatever you want to call it) as the last parameter of a method allows that method to accept a block and later yield to it. The yield statement works much the way it does in layouts, passing code execution for a time and then getting it back when the yielded code is finished.

Do make note that, like form_for, you do not use the <%= but just <% when declaring your block. This is because you aren't returning anything, but rather directly concatenating code onto the binding passed when you make the block call.

Now that was certainly useful, but doesn't really have that 'wow' factor that really makes you appreciate a new way of doing things. Let's take a stab at another common problem in app design: menu systems. Using block-accepting helpers and introducing the concept of a builder class, we can build menus intelligently and easily.

The implementation you are probably already familiar with of this type of class is the FormBuilder used in form_for. We will take that same concept and apply it to menus on a web application, taking care of a number of common headaches associated with menus. Here's the whole enchilada, and we'll go through it piece by piece. This code should be dropped into a helper:

def menu(options = {}, &block)    id = options[:id] || 'menu'    concat("<div id='#{id}'><ul>",block.binding)    # we yield a MenuBuilder so that specialized methods     # may be called inside the block    yield MenuBuilder.new(self)    concat("</ul></div>",block.binding)  end    class MenuBuilder    def initialize(template)      # by passing in the ActionView instance, we gain       # access to all of its helpers through @template      @template = template      @action_count = 0    end      def action(name, options = {}, html_options = {})      # create a local array for the classes we will be tacking on to the list item      classes = Array.new      # add the 'current' class if the current page matches the link options      classes << 'current' if @template.current_page?(options)      # add the 'first' class if this is the first time we've added an action      classes << 'first' if (@action_count == 0)      @action_count += 1      "<li class='#{classes.join(' ')}'>#{@template.link_to(name, options, html_options)}</li>"    end  end

So that should look at least somewhat familiar, right? Here's a sample implementation so that we can talk about what's going on:

<% menu do |m| %>    <%= m.action 'Home', home_path %>    <%= m.action 'Blog', blog_path %>    <%= m.action 'Account', edit_user_path(current_user) %>  <% end %>

So in just a few readable lines of code, we've done all we need for a pretty complex menu. However, because of our helper, all of the complexities are going on behind the scenes! So let's talk about our helpers. The actual helper that we call is very similar to the one we made earlier with one difference: rather than yielding with no parameters, we yielded a MenuBuilder object, which was then called in the yielded code to create menu actions. A builder can be used when there needs to be state information or more complex logic than simple helpers can provide.

In this case, we wanted to make sure that an action was marked as the first action if it was indeed the first to be called. By implementing an instance variable to count the number of actions that had been called, we are able to do this with ease. Additionally, if we ever wanted to change how the menu items were rendered, all of the changes are completely contained in the helper and builder, leaving the views unchanged.

I've found it a useful practice to stub out block-accepting helpers for any markup that I think I'll be using frequently at the start of an application. This gives the developers a chance to keep going while the design can evolve on a completely separate track. Additionally, it creates some fantastically readable code in the views.

Categories
Author
Subscribe to Css