Apr 11 2019
Apr 11

With the Twig templates replacing the old PHP templates, Drupal has been brought to a whole new “era”. We can now leverage the advantages of a component-based development in Drupal 8. But what does that mean, more precisely?

How does this (not so) new approach in software development benefit you? Your own team of developers...

And everyone's talking about tones of flexibility being unlocked and about the Twig templates' extensibility. About how front-end developers, even those with little knowledge of Drupal, specialized in various languages, can now... “come right on board”. Since they're already familiar with the Twig engine...

Also, we can't ignore all the hype around the advantage of the streamlined development cycles in Drupal and of the consistent user experience across a whole portfolio of Drupal apps/websites.

But let's take all these tempting advantages of component-based UI development in Drupal 8 and point out how they benefit your team precisely.
 

1. But First: What Is a Component?

It's a standalone piece of software that can appear in multiple places across your Drupal website/application.

One of the most relevant examples is that of a content hub. One displaying teasers of the latest blog posts, events... You could set up a component that would determine how each item in that content hub should look like.

In short:
 

  • one single component can be used by several types of content
  • any update to its template/style would automatically reflect on all those content types, as well
     

Accessible via an API, this independent piece of software explicitly defines all its application dependencies.|

Your team could then easily architect a new interface by just scanning through and selecting from the library of components.
 

2. What Is Component-Driven Development? What Problems Does It Solve?

A succinct definition of component-based software engineering would be:

A software development technique where you'd select off-the-shelf, reusable components and put them together according to a pre-defined software architecture.

“And what challenges does it address?”

It streamlines and lowers the level of complexity of otherwise intricate, time-consuming development and design processes. As the author of given components, your role is to get it implemented.

No need to worry about how they'll get “assembled”; this is what the well-defined external structure is there for.

Word of caution: mind you don't get too... engrossed in putting together the right components, in architecting the best component-based structure for you then risk investing too little time in... building them properly.
 

3. Component-Based Development in Drupal 8

Now, if we are to focus our attention on the component-based UI approach in relation to Drupal 8 software development, here are the key aspects worth outlining:

  • with the Twig engine in Drupal 8, you're free to “joggle with” extensible templates; once you've defined a Twig template in one place, we get to reuse it across the whole Drupal website/app
     
  • the Component Libraries module allows you to set up template files (storing all their needed JS and CS), assign a namespace for them and place them pretty much anywhere on your Drupal filespace (not just in your themes' “templates” directory)
     
  • you then get to use the KSS Node library and define a living style guide; it's where you'll store all the component templates built for your Drupal website (styles, markup, JS behaviors, etc.)

By filling in your toolboxes with all these tools — the results of a joint effort of the Drupal and the front-end communities  —  you're empowered to design themes that are more modular. And, therefore, more efficient...


4. The Top 6 Benefits of the Component-Based UI Approach
 

4.1. It Ensures UX Consistency Across All Your Drupal 8 Websites

Take your library of components as the “headquarters” for all the teams involved in your Drupal project: QA, business, development, design teams...

It's there that they can find the pre-defined standards they need to keep the consistency of the features they implement or of other tasks they carry out across multiple projects.

A consistency that will bubble up to the user experience itself, across your whole portfolio of Drupal 8 websites/applications...
 

4.2. It Accelerates the Process of Turning Your Visual Design into a UI 

Embracing the component-based development in Drupal 8 you'd avoid those unwanted, yet so frequent scenarios where the front-end developer gets tangled up in the wireframe he receives and:
 

  • he/she translates parts of it the... wrong way
  • he digs up all types of “surprise” issues  
     

By using a component-driven UI approach translating a visual design into a user interface gets much more... event-less. 

With:
 

  • a pre-defined component architecture to rely on
  • well-established standards to follow
  • a whole library of component templates at hand
     

… there are fewer chances of discrepancies between the UX defined in the visual design and the one delivered via the resulting user interface.

Not to mention the reduced delivery timelines...
 

4.3. It Streamlines the Whole Development Process 

“Sustainability” is the best word to define this approach to Drupal software development.

Just think about it:

  • whether it's a particular grid, navigation or layout that your front-end developer needs when working on a new project, he/she can pull it right from the component library at hand
     
  • … and “inject” it into the app/website he's working on
     
  • in case that element needs further updating, the developer will already have the baseline to start with
     
  • … there's no need for new components to be designed, from the ground up, with every single project: the already existing ones can always get further extended

And that can only translate into significant savings of both time and money.
 

4.4. It Reduces the Time Spent on Setting Up the Functionality & Defining the UX

And this is one of the key benefits of using component-based development in Drupal 8. Your various teams would no longer need to define the UX requirements and the functionality every single time during the design process.

With an easily accessible library of components, they can always pull a component standing for a specific requirement (display of complex data, filtering, pagination in grids, etc.) and just define its extensions. And the business logic, as well.
 

4.5. It Enables You to Systematically Reuse Your Components

And “reusability” goes hand in hand with “sustainability”. I would even say that it's a synonym for “future-proofing”, as well...

Just think about it: having a Drupal 8 website in a component-based format you can always rearrange components as technologies grow outdated and new ones emerge...

In short, embracing a component-based development in Drupal 8 enables you to remove the need of rebuilding your website every time its underlying technologies “grow out of fashion”.

With your component library at hand, you'll be able to swap your guidelines, design patterns and various content templates in and out, keeping your Drupal app or website up to date.
 

4.6. It Integrates Seamlessly into the Development Process 

By leveraging a component-based development in Drupal 8, you'd also gain better control over the whole development cycle. The update process here included...

Since you'd then build your components and manage your production quality user interface code in a repository like GitHub, every update that you'd make will be displayed in there. And be easily accessible to everyone in your team.

In short, your developers get to pull pieces of code from the repository to further extend them, then re-submit them to GitHub (or to another source code repository) for review.

With the ability to version your component library, your team can keep a close track of all your Drupal applications with their corresponding versions of the approved UX.
 

The END!

This how the component-based development in Drupal 8 would benefit you and your team. Have we left out other key advantages of using this approach?

Image by Arek Socha from Pixabay

Feb 28 2018
CSS
Feb 28

Automate all site-building tasks and streamline your theme development process! In short: reduce development time and boost your productivity as a Drupal 8 themer with Gulp! But how to use Gulp to automate your workflow?

How do you set it up and run its toolchain in conjunction with Drupal? How do you move away from the old practices of the “good old days”,  when you had to write your themes in pure CSS?

Since you had no alternative...

How do you “harness Gulp's power” to automate tasks that are crucial for your Drupal 8 theming process such as:
 

  • compiling SASS and LESS
  • watching/generating CSS files from SASS
  • testing
  • generating static design pattern pages
  • reloading the browser 
  • optimizing assets: images, JavaScript, CSS
     

Well, keep reading and “thou shalt find out”!
 

But What Is Gulp, After All?

I confess I couldn't come up with a better definition for Gulp, than the one on the official site:

"… a toolkit for automating painful or time-consuming tasks in your development workflow, so you can stop messing around and build something."

More often than not referred to as “build tools”, Gulp is a front-end automation tool aimed at streamlining your theme development process.

Basically, it enables you to have all those tasks that are critical (and time-consuming) for your workflow run... automatically!

And thus to give your productivity as a Drupal themer a significant boost!
 

Why Use Gulp over Other Theme Development Streamlining Tools?

Here are 3 of the strongest reasons why:
 

  1. because Gulp configurations are conventionality simpler, shorter
  2. because using Gulp you get to capitalize on a wider community support
  3. because it runs faster, as well
     

How to Install Gulp

A word of caution: since Gulp is a node module, make sure you install Node.js (this, of course, if you haven't installed it already) first things first.

Needless to add that:
 

  1. you should go for the latest version of Node.js
  2. the installation process depends (and may differ) greatly on the Operation System that you're using
     

Install Homebrew, then run the following command:

$ brew install node

Now, for installing Gulp, type the following command:

npm install gulp-cli -g

Where “npm” stands for the “Node Package Manager” used for installing Gulp on your PC. And where the “-g” flag signals that Gulp should be installed globally on your PC.
 

Creating Your Gulp Project: Set Up Your Package.json File

As you well know, Node.js uses “npm”, a package manager “in charge” with downloading and installing all the modules required for a given project.

And all these modules get defined in a “package.json” file. 

So, this is the step you, too, should take now: setting up your package.json file in the very root of your Drupal 8 installation.

For this, just run the following command inside that directory:

npm init

It's inside this newly created package that all the key information about the node packages required for your specific project gets stored!

Therefore, make sure to fill up all the needed information as you put together your package.json.

Note: still, you should also know that all the prompts are ideally intuitive and that even if you leave those fields blank, you can always come back later and change the default values.

Remember to set the entry point to “gulpfile.js” and, once you add the required information for your project, keep in mind to specify your git repository.

An Important Word of Caution!

Your “How to use Gulp to automate my theming tasks in Drupal 8?” question should be accompanied by: “How to prevent triggering a segmentation fault?”

One that you might involuntarily trigger once you run Drush. Since Drush will consider the node package's own .info file files as part of Drupal and since it doesn't recognize their format... trouble happens.

Here's how you avoid segmentation fault:

add a script to the package.json file, whose main role will be to remove all the .info files from the node_modules folder

And now, let's go back to our package.json setting up process!

One last piece of advice that I'd like to add: if you've run the “npm init” command for creating your package.json file, remember to identify the “scripts” section and to replace the following line:

"test": "echo \"Error: no test specified\" && exit 1"

… with this one:

"postinstall": "find node_modules/ -name '*.info' -type f -delete"

And one more thing: set up the following .npmrc file in your theme folder's root:

unsafe-perm = true

Here's how the “intro” of your package.jso file' structure will look like:

"name": "...",
  "version": "...",
  "description": "...",
  "main": "...",
  "author": "...",
  "private": true,
  "devDependencies": {
    "browser-sync": "...",
    "gulp": "...",

Once you have your package nicely set up, go ahead and install Gulp into your project by running this command:

npm install gulp --save-dev 

Note: you might be wondering why you need to install Gulp... again. The answer is simple: first, you installed Gulp globally and now you're installing it into your Drupal project!

In this respect, it's  “--save-dev” which will let your PC know that Gulp needs to be added as a dev dependency in your packgage.json. All Gulp files and dependencies associated with it will get downloaded and a “node_modules” folder will get created.
 

Set Up Your Gulpfile.js

You're not yet done with setting everything up! There's still one important step to take before you discover how to use Gulp to create and to automate your site building tasks: setting up the gulpfile.js!

For this, just:
 

  1. go to your custom theme directory
  2. manually create a gulpfile.js file by either using the cmd/terminal or just by right-clicking to create a new file
     

Note: keep in mind to change the config variable so that it should match your paths! Also, make sure that all your CSS gets stored in the same “CSS” directory in your theme (for example: sites/all/themes/my_theme/css/application.sass) 
 

How to Use Gulp to Create and Automate Key Tasks for Your Workflow

And finally, we've reached our “destination”! 

The very goal of this blog post after all: determining which site building tasks are crucial for my/your own workflow, creating them and then automating them all with Gulp!

Do you fancy automated:
 

  • Sass compiling into CSS?
  • cache clearing
  • “detection” of all the changes you will have applied to your .scss files?
  • page reloading?
     

And your “wishlist” might go on... 

Well, the answer to your “How to use Gulp to automatically run task “x” or “y”?” is simple:
 

Just run the gulp [task_name] “magic formula” in your terminal! 
 

Here are some examples: 
 

  • gulp.task('watch', function () which will watch for all the changes applied to your scss files and automatically recompile 
  • gulp.task('reload', ['clearcache'], function () which will clear cache, then automatically reload the page 
  • gulp.task('browser-sync', function() which will automatically run the BrowserSync server


In order to get the whole process started, simply type “gulp” in your terminal.

The END! Your turn now!

Time to use Gulp to its full potential and to automate all those key (and time-consuming) aspects of your theme development process in Drupal 8! 

Jul 20 2017
CSS
Jul 20

Would we be wrong if we stated that the very “easiness” of writing CSS code is this language's “Achilles' heel”, too? It “lures” you in, it boosts your confidence as a programmer and than... nasty surprise... your web projects gradually turn into unmanageable messes! This is why the need of building out a CSS architecture, that we can organize and structure our CSS codebases by, has rapidly gained importance in developers' community!

And where do you add that there are multiple well through-out methods for you to use for neatly and effectively structuring your CSS files! We've hand picked just 5 of them, “la crème de la creme”.

But before we go on with our CSS organizing techniques, let's “look our enemy in the eye”! Let us highlight the challenges that we're currently facing while trying to effectively managing our CSS projects:
 

  • it uses global namespaces, leading to inevitable collisions and leaking styles
     
  • it's purely declarative: zero logic and no well structured workflow which would let all the other developers working on the same project know about the state of the project itself
     
  • it operates with inheritance: meaning that everything is interdependent and, therefore, highly “fragile”, prone to getting broken  
     

And the list can go on. 

So, now that we've pointed out the obstacles that we need to overcome when it comes to “taming” our load of CSS files into a scalable, easy to maintain CSS architecture (suitable for long-running, large projects, needless to add) let us point out to you the 5 “chaos proofing” methods:
 

Which stands for “Object Oriented CSS”.

The whole “philosophy” behind this CSS structuring and planning method revolves around the idea of creating pages/views by putting together multiple CSS objects! CSS objects which are independent from one another (see, the CSS's interdependence issue that we've just pointed out in our list of “drawbacks”).

And when we say “independence” from a CSS code's standpoint, we can only imply that:
 

  • design and structure are separated 
  • container and content are independent of each other, as well 
     

And this whole “separation of concerns” driving principle has 2 major results:
 

  1. the entire “load” of code gets considerably lighter (and this is a tremendous asset if we take large, code-packed web projects into account)
     
  2. yet things get trickier the moment one of your Toronto developers tries to apply a change to a certain element's style: not only that the CSS will need to be modified, but classes will have to be added to the markup, as well 
     

“Scalable and Modular Architecture for CSS”, a style “guide” (rather than a strict framework) developed by Jonathan Snook.

Now this approach to organizing your CSS code is more than “tempting”: it promises you a lighter code “cargo” and simplified code support.

What more could you ask of a CSS organizer, right?

Moreover, this technique operates with 5 sets of rules:
 

  1. base rules: targeting a site's main default elements such as body, HTML, a:hover, input, button etc. They target your CSS assets, too, and “constrain” you to use attribute selectors and HTML tags mostly (and classes, too, but extremely rarely)
     
  2. layout rules: which segments a web page into multiple sections including global elements such as header, footer, sidebar, article, defining each one's style too. 
     
  3. modules rules: includes reusable blocks, modular elements that you get to use several times on the same web page. Keep in mind, though, to avoid using tag selectors and id for module classes!
     
  4. state rules: define the various statuses of those modular elements (e.g. hidden, active, inactive etc.). Moreover, you should know that all these variations get prefixed as following: is-active, is-hidden.
     
  5. theme rules: define the design styles, how your modules will look like and they're particularly useful in case of larger sites with shared modules having different layouts throughout the websites.
     

Note: take the SMACSS approach as a guideline rather than as a strict method, or a set of rigid “rules”. As a web developer who'll use this method to build a well-structured, maintainable CSS architecture, you'll still be free to use your own namespaces for your class categories, to display them to your liking and so on. The only “common sense” rule is that of documenting your CSS code, so that all the other developers in your team should easily follow you along.

But this “rule” stands irrespective of the CSS structuring approach that you might decide to adopt, right?
 

3. BEM, An Increasingly Popular Methodology for Building Out a CSS Architecture 

… or “Block Element Modifier”, if you prefer, developed at Yandex!

Expect it to be more prescriptive than SMACSS (for instance). BEM is more than just a set of basic guidelines: it delivers a strict method for you to structure your CSS classes into independent modules!

And speaking of this method, although you'll find multiple variations on it, the basic structure looks like this:

.block {}
.block__element {}
.block--modifier {}
.block__element--modifier {}
 

It's only just “fair” that we presented each one of this structure's components right? 
 

  • a block: any object on your site (a menu, a person, a login form)
     
  • an element: part of a block performing a certain function in the context of that block only: a login button, a menu item...
     
  • a modifier: the way you'll represent the variations of a given block (a search input field having a particular button style, a menu “tailored” to adjust itself to a footer or a sitemap etc.)
     

Key Advantages to Using the BEM Method as a “Backbone” for your CSS Architecture:
 

  1. it's perfectly scalable, being a perfect fit for both small and large projects
     
  2. it keeps you from nesting selectors (a well-known drawback when it comes to Sass codebases) thanks to its long, descriptive class names
     
  3. it enables you to reuse your code: basically it works as a “code container” for you, which turns out to be a major asset especially if you're working on a large project where your team has to move “clusters” of CSS, JS and HTML code from one project to another
     
  4. it's ideally suited for large, modular web development projects
     

… or maybe you prefer “Functional CSS” instead?

As for this CSS “organizer's” philosophy, so to say, we could formulate it like this: creating one separate, single-purpose class for each and every reusable property, while naming it according to its visual function!

The undeniable advantages of such an approach to organizing your CSS code are:
 

  • a significantly lighter load of CSS code, since you'll get “empowered” to reuse your declarations
  • an easy way to modify code (it makes applying changes to your modules less complex, for instance)
     

Yet, this method does come with its own flaws, too. Here are some of the most “painful” ones:
 

  • the class naming conventions come along with a high learning curve, too
     
  • it makes the style code closely linked to the Atomic CSS framework used for generating the classes
     
  • the class names aren't semantically linked to the elements, but rather describe property names 
     
  • the display settings are in the HTML
     
  • as new CSS modules get added to the specifications, everything gets overly complex 
     

Note: Atomic CSS has “succeeded” to split developers' community into 2 major groups: those that keep highlighting this methodology's major flaws and those that, on the contrary, qualify specifically these flaws as benefits instead:
 

  1. the “semantic nature” of the elements are, in their opinion, already properly described by the element tags and your components' names
     
  2. the fact that the settings are displayed in the HTML might turn out to be more convenient: this way you won't need to go through your entire maze-like CSS codebase to find out what settings are defined there

5. ITCSS: Build Your Manageable CSS Architecture for Large Projects

Harry Roberts' “Inverted Triangle CSS” implies, as the name suggests: visualizing and structuring your project as a triangle. An upside-down one!

This triangle-shaped structure would include the following “layers” of CSS code:
 

  • Settings
  • Tools
  • Generic
  • Elements
  • Objects Components
  • Trumps
     

Practically, the IRCSS technique “constrains” you to order your CSS codebase not by the usual human-oriented patterns, but by those metrics defined by the programming language (along with its particularities) itself!

Ordered this way, your code will get better “understood” and “exploited by both browsers and by the specific design of the programming language itself. It will no longer get organized by how a person thinks, but rather adapted to the language's own features and to the way browsers perceive it.

This way, your ITCSS-based CSS architecture will end up to be:
 

  • easily scalable
  • logical
  • manageable 
  • predictable
  • rule-based
     

... instead of an “untamed mess”! 

Which one of the above presented 5 methods better suits your team's coding style? Your current project's specific needs and requirements? Go for the one that you find more suitable for your own team's specific workflow, coding style and for your web project's particularities and get your own “unmanageable CSS mess” ideally structured, too!

Dec 07 2016
CSS
Dec 07

How many times haven't you heard this line: “There must be a CSS for that!”. You might have said to yourself: “yeah, right, like CSS could be the answer to any coding dilemma”.

You'd be surprised: in way too many cases it actually turns out to be that “magic formula” you need. And it would be a pity not to make use of CSS's helpful resources. With only one or a few more lines of code CSS works its magic for you, lifting a heavy weight off your shoulders!

Enough beating around the bush now: we'll go ahead and share with you our top favorite CSS tips that will help you improve and thus speed up your workflow:
 

1. Center Your Content Vertically

A bit frustrated for there is no “official” method (yet) for centering content within its container in CSS?

We've been there, too, you know. And here is the solution that we're happy to share with you after our own experience of striving to align text in CSS: the line-heightproperty.

Let's use it in an example:

.nav li{

    line-height:50px;

    height:50px;

}

Note: make sure that your line-height value is (almost) the same as your container's height!

Furthermore, you need to keep in mind that this method applies only to single line texts. If you're dealing with a multiple lines text, going for this solution will only add too much white space to your website (it's logical if you consider that the same line-height value will be applied to the space between those lines).

So, stick to single line texts such that of navigation menus when applying this CSS trick. 
 

2. Dealing With CSS Tables 

We'll just have to accept it now: there's nothing we can do to turn back the hands of time and make up for all the time “wasted” when we didn't use display: table for handling CSS layout. 

So, let's sum up our “findings” regarding this CSS “trick”.

First, you can use display: table for efficiently:

  • setting equal heights for neighboring columns (it's true, you can also use JavaScript for that, but: oh boy! isn't JS a lot heavier and packed with its own particular drawbacks!)
  • centering an item, vertically, next to a larger one  

And now if you're still a big hesitant to replace the conventional “table layout” with this new “formula”, let us add that unlike it, this “new” (although it's been specified in CSS even from its 2.1 version) can quickly be turned responsive: you just need to add a breakpoint for removing the display: table. 

There' more! Here are other 2 “great things” that you can achieve with this CSS solution:

  • float-less grids
  • tables without the <table>
     

3. A Few Words About Transition

How are you responding to the challenge of puling of hover effects on the websites that you're building these days (for gradually changing the menus or the images' colors)? Admirably? OKish? Or really badly?

Well, if you've been having trouble creating really smooth effects, CSS is ready to lend you a hand. Just take a look at this example here:

.entry h2:hover{

    color:#f00;

    transition: all 0.3s ease;

}

Why should you replace the old JavaScript technique for creating hover effects? Because you're in a highly competitive world (the online world), where you simply can't afford not reaching for “perfection” (instead of "second best").

In other words: why should you stick to jarring jQuery animations (or to the much heavier JavaScript) when you could go for a more time-effiecient (just an additional line of code, no need for you to learn a new language if you're a coding newbie) smoother hover effect?

So, it's a win win situation: for you and for your website's future visitors!
 

4. Aim for The Absolute Positioning

Centering in CSS is probably the ultimate source of “frustrations”!

With all those different elements, requiring different CSS properties before they can be “tamed”/centered, “absolute positioning” sure sounds like a beautiful utopia, wouldn't you agree?

But it can become reality: you just need to start using the position property. Like in this example here:
 


position:absolute;

top:20px;

right:20px

Just type in bottom, top, left and right and add a pixel value to each one of them, thus keeping a steady control of where your element will be positioned on your website.

For instance, in the above example we've set that the element should be positioned at 20x from the top.

Note: this CSS trick works wonders when you're dealing with a single child element (otherwise the other element within the same container will get affected)
 

5. Pull Off the “Storybook” Effect

You love it, we love it, they (your website's visitors) sure love it!

The storybook effect, you know, the one focusing on capitalizing the first letter of a page/paragraph is still so loved since it reminds everyone of all those old story books brightening up their childhood memories.

So, why not recreate this attention-grabbing typographical effect on your website? Especially, when it's so quick and easy to do it in CSS? 

The :first letter pseudo element is the CSS “trick” you need to use for puling off this "traditional printed book" effect.

p:first-letter{

    display:block;

    float:left;

    margin:3px;

    color:#f00;

    font-size:300%;

}

You can just see, in the example above, how you can use :first letter, plus specific pixel values, for targetting the very first letter of the first line of the selected element on your website: here it makes it 3px wider than the rest of the letters in the text.

And these are just 5 CSS tricks that can help you create better looking websites. They “aim” for guaranteeing both a better user experience and less sleepless nights and moments of frustration for you and your team, too.

Give them a try, run some tests and find our if they'll boost your efficiency as web developer/s, too!

May 11 2016
May 11

Bootstrap is a giant framework with almost everything you could need for building a site or web app interface. Bootstrap is changing, version four is in alpha release. Naturally, we’re just as curious to know what’s different, so I dived into the documentation to find out. Keep in mind, though, that this is an alpha release. It cannot be considered feature-complete. It could radically change.

From Less to Sass

This is obviously the biggest and most important change. Heck, you’ve probably already heard of it. People have gone so far as to procliam the “death of Less” due to this switchover. Well, I don’t know if anything’s gone and died because the Bootstrap team decided to do things differently. It is, however, a monumental undertaking, and it will drastically change how people use and customize the framework. Sass is just generally more developer-friendly, with wider support, a bigger community, and yes, more features. It can do some things that, right now, Less just can’t. I say this with sadness. I’ve never made any secret of my love for Less; but it seems that the community at large has spoken, and declared that Sass is just, well, better.

New features

Figures

Figures are for showcasing single media objects (usually images), with an optional caption. Support for Bootstrap’s various helper classes is factored in, so you can align and style the image (and its caption) however you like. Images placed in a figure element, given the right classes, become responsive automatically.

Flexbox

Now, due to lack of support, Flexbox has not replaced the regular grid system. However, it is available to anyone who wants it. Change a variable, recompile the Sass, and boom! You now have a new, modern layout system.

Cards

Okay, we’ve been seeing the proliferation of card-based design for some time now. Bootstrap now has a specific component for them, with myriad layout options. You can group them up, keep them separate, add headers, footers, buttons, images, and overlay text on those images. Wells, thumbnails, and panels all get replaced by the new card component, so in that way, Bootstrap is a bit more streamlined.

Reboot: new customization variables

Bootstrap has historically been a bit of a pain to customize, aesthetically speaking: There were a lot of styles to over-write, and individual variables to customize if you wanted to make your Bootstrap-based site look like anything other than a Bootstrap-based site. Heck, remember all of those customization apps made just for changing Boostrap’s look? Well the developers have heard your prayers and Github issues. Change all of the transition animations at once, disable rounded corners, change all the colors, or anything else you like with one big bunch of Sass variables. It’s all there in the Reboot module, and it’s about time. We can expect some more original-looking designs now, with any luck.

Rem and em units

That’s right, we’re moving away from pixels, to these relational units of measurement. This ties into the whole customization thing, too. Want a tighter design with thinner margins? Change the main text size, maybe a couple of variables, and boom. Everything looks “thinner”.

Stuff that’s basically the same

As you might expect, everything got re-written and upgraded (because of the Sass move). But still, the basic usage for most of these components will be the same. Do double-check the documentation, though. Certain things will have changed. Take the grid, for example: they added an “extra-large” tier to the grid system, presumably for those ridiculously huge retina screens that we’re seeing these days. · Alerts · Breadcrumb · Button dropdown · Button group · Buttons · Card · Carousel · Code · Collapse · Dropdowns · Forms · Images · Input group · Jumbotron · Label · List group · Modal · Navbar · Navs · Pagination · Popovers · Progress · Reboot · Scrollspy · Tables · The Grid · Tooltips · Typography

Other updates

No more IE8 support

It’s about time. There’s not a whole lot more to say about that. Not much will change for most of us. Anybody who really, really needs to support legacy browsers will have to use an older version of Bootstrap.

All JavaScript plugins have been re-written

The proliferation of ES6 means that a lot of people are re-writing their JavaScript. This means performance improvements for all, the exodus of older browsers, and programmers having fun with new toys. It’s a win-win.

Overall impressions

Where Foundation is going “smaller” and more streamlined with specialized frameworks, Bootstrap seems to want it all. They have done a lot of work to improve performance, and streamline what they could, but Bootstrap still aims to do just about everything you can think of. Mind you, anyone can configure their version of the framework however they like by dropping unnecessary modules, or adding new ones. It’s not a big deal. Still, there’s definitely a one-size-fits-all mindset in play. And that can be a good thing. There are large, wide-scope projects out there that need the room to expand. In any case, Bootstrap will continue to satisfy its users’ needs. It’s going to be mostly the same, but better.
Source: http://www.developerdrive.com

May 02 2016
CSS
May 02

CSS is very flexible since it doesn’t impose on how you should write your CSS rules but putting CSS rules in different spots can make your stylesheet less predictable than what you’d want to go for. Maintainability problems will most likely arise when the CSS selectors cascade – this applies to other CSS pre-processors such as Sass and LESS as well.

In most projects the SASS code follows the DOM structure – this means that the CSS structure is linked to the DOM. This can result in larger file sizes and the component becomes non-reusable. If the markup needs to be changed or moved, the CSS rule needs to be changed as well. Using ID selectors could lead to maintainability problems.

At this point most developers would try to write a stylesheet with very specific rules – since there can be only one single element using the same ID, these are not reusable. Other aspects include ever-longer CSS files – some have over 1000 lines of code.

Think Components

Think about the fact that a web page is composed of multiple components. Let’s take a services page as an example. The page is composed out of three components:

  • Services is the entire services section
  • Container is simply a generic container that limits size and adds some padding
  • Service-item is a single service item

Styling VS layouting

In order to make a component easily reusable and to make the CSS layout more manageable, the concepts of styling and layouting need to be differentiated.

Styling means changing paddings, borders, fonts and colours. All these changes take place inside the component itself and hence do not interfere with the layout or structure of other components. The following elements fall into styling:

  • Text align
  • Padding
  • Font
  • Colour
  • Border
  • Background

Layouting on the other hand implies moving elements around your page and sizing them – this can affect other elements on the page. The following fall into the layouting category:

  • Height and width
  • Left, bottom, right or top
  • Transform
  • Position
  • Margin
  • Float
  • Clear

Do not layout yourself

You shouldn’t layout yourself because a component should style itself but give up the task of layouting to its parent. What this means is that the component doesn’t need to float on its own or have its own margins but the parent-component should layout its child components.

This makes it much easier to build responsive user interfaces because the layout itself becomes more predictable. There’s no need to worry if two components look good on a screen if the parent component layouts its child component appropriately.

 

Components should be simple

If your components have too many lines of code, you should create a different component to handle it all. In the same time, having too many components can turn into a maintenance burden – hence the option to create sub-components.

Nesting subcomponents together is not allowed, so if the subcomponent needs to have its own sub-components then it should become a top level component. These rules are enforced in order to keep components simple and working smooth.

Component inheritance

Sometimes a component is a specialization of another component. Adding modifier classes to the HTML markup could make it redundant and not friendly to refactoring. By using Sass we can use @extend in order to extend other components. Eg: The “services” component is a specialization of an inverted section. In this case we use @extend only for component inheritance, which is a valid use case. It’s possible to use either @extend or @mixin as long as both are used in a controlled manner.

The bad thing about using @extend is that it won’t necessarily work for generated CSS files and you can’t extend from inside a @media query. If it needs to be done, the CSS structure needs to be reworked.

 

File structure

CSS files with a large amount of lines are very hard to work with. In some cases, depending on the project’s complexity, it may be possible to put all the CSS code in a single file. For larger projects it may necessary to organize assets via controller.

Directory structure

Having stylesheets with a large number of files can be very difficult to handle, so grouping them accordingly is crucial – keep in mind that each project is different and each directory structure needs to be different. Try to find a directory structure that fits your current project. Sometimes you can put all the CSS in a single directory but at other times you need to organized them by type, media type or screen size.

Wireframe – Design – Wireframe

Sometimes it’s a good idea to draw another wireframe from the already finished design. But why?

  • With the wireframe in place we’re able to look at the page as a whole, not just little portions.
  • Naming and componentization – viewing the whole page in a glance lets you name sections easily
  • Hierarchy and structure – it’s easier to structure your pages into sections or subsections with the wireframe in place
  • Margins – with the wireframe you can plan your paddings and margins more efficiently

 

Responsive design

Breakpoints can be defined for desktop, tablet, mobiles or they can be created based on content. Creating breakpoints based on content means that the site will look good on any screen size. Start with the smallest screen size and resize your window accordingly. When a component looks out of place, modify it and create a breakpoint there. Repeat the process until you reach the largest screen size you want to support.

Conclusions

These are the basic ways to write more predictable and maintainable stylesheets – by applying these tips you’ll save yourself a lot of tweak work in the long run. Happy coding!

Apr 28 2016
Apr 28

Every expert from every field has his or her own tools of the trade and web development is no different – web development tools are one of the most important factors to every project and these tools could mean the difference between finishing your project on time or passing multiple deadlines. Luckily enough, plenty of top web development tools are available for just about every platform. Here is our list of OS X apps which you should include in your web development tools box:

Browsers for web development

One of the most important tools for web development is a browser – you’ll need to view your website after you created it right? But it’s not so simple – you will need to test your website for many browser versions, including beta and nightly builds. With that taken into consideration, you’ll most likely need Opera Next, Chromium, Chrome Canary, Firefox Aurora, and Firefox Nightly.

Koala

Koala, apart from its cute name, is another nifty web development tool which is used to compile CoffeeScript, Compass, Sass, and LESS into a browser-compliant format. If you’re using any of these techs, Koala is definitely a must.

Anvil for web development

Anvil is an interesting free app which allows web developers to create .dev domains. You’ll see it as a new icon in the OS X menu bar and you can turn it on or off, create domains or add your projects to it. If you’re looking for a tiny web development tool to manage or work on your local websites with, Anvil is perfect.

Keka

When handling multiple files, you need a reliable compression service to help you along. Most web developers may use ortar, rar or zip but Mac has its own built-in feature to extract and manage these formats – this service is rather limited so you’re better off with Keka. Keka is a free open source OS X app for file compression and extraction.

Keka supports zip, rar, ortar, ISO, DMG, Tar, Gzip, 7z and it can extract to PAX, CAB, EXE and RAR formats. Keka allows you to split compressed files into different parts of specified sizes, apply password restrictions or automatically delete source files after extraction or compression.

Web development & Web Sharing

Since Apple removed the Web Sharing option from the OS X system preference, you might want to install the Web Sharing plugin. This little plugin will allow you to host local websites under the local host address. Once you install it you’ll be able to see a new panel in System Preferences – here you’ll be able to switch web sharing off or on.

File compression, One of The Very Top Web Development Tools for Mac OS X

We talked about Keka before but there are two ways you can use it to compress files. You can either download this small web development tool and install the services contextual menu or you can drag and drop your files directly into the Keka app window.

Sequel Pro

MySQL is one of the most popular databases in the world – plenty of websites rely on MySQL for storing and managing databases. If you are using OS X, Sequel Pro is a must-have for web development. It’s a native OS X app built in Cocoa and it also features a nice and friendly GUI. With Sequel Pro you can create, filter databases, import, export, remove, create users and execute MySQL queries.

The iPhone Emulator

All web developers need to take mobile users into account when building their websites, hence the need for a web development tool that can be used to test websites for specific platforms. Devs can use physical tablets or phones or they can go for the easier option – a simulator like iPhone Simulator. All you need to do is just install Xcode from the AppStore and you’re done – you have another web development tool in your little toolbox.

Icons8

If you’re looking to use icons, Icons8 is one of the top web development tools that you can use. Just install Icons8 and you’ll be able to search through its over 2800 collections of icons. Once you find something you like, you’ll be able to copy it to Finder, Xcode or Photoshop.

Github and SourceTree

Even if you’re building a small website or a presentation website, you’ll need a control version system to track your revisions and changes to the project’s code. Github is the most popular service for version control and you can install it on OS X as well. SourceTree is another mentionable service – both of these services are the backbone of any respectable web development agency.

Poedit

Poedit is the best web development tool you can use for translating websites into multiple languages. Not only that but you can translate plugins and Wordpress Themes as well with this little app.

Automator

Automator is a web development tool that’s pre-installed with OS X. This little app allows users to automate tasks such as cropping multiple images at once, creating thumbnail images, changing file extensions and renaming files in batch.

Dash

Dash collects documentation for a lot of the popular programming languages, including LESS, Sass, jQUery, CSS3 and HTML5. Users can search through code snippets, functions, syntax, and other valuable information.

Apr 25 2016
Apr 25

As we all know, programmers and designers don’t have a lot in common in terms of workflow or the software used to complete their tasks. Communication and synergy between programmers and designers can either make or break a project.

How can you improve your work with a programmer? Implementing a clear workflow and respecting it is crucial – both parties need to provide feedback as work continues and a clear plan of action needs to be set in place for the current project.

Start planning your project

Simply shipping your design work over to the programmer may work on very small tasks or smaller projects but for larger, more complex projects it could turn into a disaster. The workflow needs to be accompanied by careful planning.

Your average plan should include a schedule estimate and an approximate cost. If you’re building the project for a client, cost estimates are mandatory. Project planning needs to also account for how an optimal collaboration can be reached – the small details count in this phase.

Prepare your design for coding

Instead of simply handing over your design work along with a few requirements to the programmer and waiting for the results to appear, designers need to also focus on things which will enable the programmers to help them in the long run.

Here are a few aspects and tips you need to take into consideration when producing your design:

Your key objective is Pixel Perfect – If you want your programmer to implement your design work properly, you need to provide him with exact details – elements such as colours, style, fonts, margins and padding need to be specified exactly before the programmer can begin his portion of work.

Keep in mind that by doing this you eliminate the need for future changes or revisions – as a result the overall cost of your project will be reduced.

Follow Photoshop Etiquette – Designers should properly name layers and structure their files accordingly. Images need to be aligned and the programmer needs to be provided with plenty of information – it goes a long way in building your project and speeding up your workflow.

Keep in touch with the coder – It’s a good idea to maintain contact with the coder on a regular basis and ensure he has all the information he needs to properly do his portion of the project. Developers really appreciate it when you provide your support.

Designs for interactions are important – These designs can be a great help to your coder as well. Examples can include the intended use of sliders, button hover states, dropdown menus and others.

Research on the technology used – You’ll get a better understanding of what’s feasible from a programming point by keeping up to speed with the latest tech trends. Sometimes designers may ask for features which are simply impossible to implement.

Don’t rush, time is plenty

Planning ahead, coordinating your work and providing clients with meaningful estimates will save you a lot of time in the long run. Transparency will help all people involved to get a better understanding of the overall project and speed up the workflow.

Apr 07 2016
Apr 07

I’m not a fan of color theory. But the theory has always eluded me, and, truthfully, I’ve never found it useful when trying to use color in my projects. Somewhat ironically, I’ve been finding that the better I get at choosing and using color, the better I become in the theory behind it. Of course, that doesn’t really help when you’re just starting out, does it? That’s why, in this article, you won’t see a single color wheel. Instead I’m going to show you a simple color workflow that you can use in your next web project. You will, of course, subconsciously be learning the theory along the way. So, I recommend coming back in a few months time and giving the theory another go.

Choosing A Base Color

We can see something like 10 million colors at any given time, that’s a huge amount of colors. And out of those, we need to choose one — just one color — to be the base of our website, for our brand. Everything will stem from this one color, so it’s kind of important.

How to choose a starting color

Now, picking a color out of the blue (pun intentional) would be quite easy, but we’re not going to do that. For any project in which you’re having contact with clients, you should try to justify as many of your choices as you can. If you don’t, it’ll be a case of your favorite color versus their favorite color. They’re the client. They’re paying you. They will win. Don’t think too much about it. Just make sure you have some kind of reasoning behind your color choice (and every choice, for that matter). It’ll make you look good.

Tips on choosing a starting color

• Use what you have. If the client has a logo with an established color, that will usually be your starting color. • Eliminate your competitors’ colors. If one of your main competitors has a strong brand color, don’t copy it if you can help it. Find your competitors’ colors to eliminate them from your own color schemes. • Think about your target audience. The colors of a website for a pizza shop would sure be very different from the colors for a kids club. Think about who will be using the website and how you want them to feel (excited, serious, taken care of, etc.). • But don’t default to stereotypes. If you’re designing a website for young girls, you don’t have to use pink. Avoid clichés to gain credibility. • Play a word game. If you’re struggling, write down any words that you associate with the client’s business. This list should give you some ideas for colors. If you’re really struggling, hop on any website about color meanings and see which fits best. You should now have a base color in mind for the design. It should be something simple like red, green, blue, yellow or pink. We’ll get to the exact shade next. Let’s say you choose blue.

Choosing A (Nice) Base Color

Instead of messing about with Photoshop’s color-picker to find a nice shade of blue, we’re going to steal like an artist and use other people’s design choices to help us out. First, go to Dribbble.com and Designspiration.com and click on the “Colors” link in both. You can use this as the next step to find the right shade of blue. For a fresh and energetic brand, go for one of the lighter, brighter blues (one of the top five options). For something a bit more corporate and serious, the bottom five should be a better fit. Choose a shade from each website to see actual designs that use that color. You can then use any of CSS-Tricks’ color-picking techniques to grab the exact colors right in the browser. Not only will you see different versions of your base color, but you will easily see colors that match.

Creating A Strong Color Palette

All right, you should now have a HEX value for your color. Now we’re going to make a palette out of that color. And it’s easier than you think. The problem with this kind of color palette is that applying it to a real design isn’t very practical. Most palettes have way more colors than you’d ever need, especially considering that we need to add an average of three neutral colors to every scheme: • white, • dark gray, • light gray (optional). If you tried to add five or six colors to the neutrals, it would be a mess. All you really need are two colors: • a base color, • an accent color (we’ll get to this in a jiffy). If you can create a website using only these five colors, you’ll get a much better result than if you were to go overboard with complementaries, split-complementaries, triads and the rest.

Finding your accent

Your accent color will be used in very small amounts on your website, usually as a call to action. So, it needs to stand out. Your next step is to go to Paletton.com and type your HEX code into the color box. From here, you can find your accent in two ways. First, you could click the “Add Complementary”! That yellow there? That’s your accent. Alternatively, if you don’t like the color it has generated, you can click around the icons at the top to find something more suitable. Personally, I quite like the red that comes up under the triad icon, so I’m going to use that for our scheme. There is, of course, science and stuff behind what Paletton is doing; but, for now, let’s put a pin on it. You’ll learn the theory a bit later, and all will become clear. So, below is our color scheme as it is now. We’ve got a nice base color and a shot of an accent. Let’s add white to the mix, because white is always good. All that’s missing now are some grays.

Adding the gray

For most of my web projects, I find having two shades of gray to be infinitely useful — one dark, one light. You’ll use them a lot. The dark is usually used for text, and the light for when you need subtle differentiation against all that white (usually for backgrounds). You can choose your grays in one of two ways: • You could use Dribbble.com and Designspiration.com again to find a nice gray from your previous results that matches your base color. But usually it’s easier to type blue website in the search bar, which will show more grays in the results. • If you have Photoshop or the like, you could use Erica Schoonmaker’s technique to harmonize your grays with the base color.

Creating harmonious grays

To get our shiny new harmonious grays using Erica’s method, we’ll start by picking two default grays out of a hat. Then, follow these steps: 1. Create two shapes and fill them with #4b4b4b and #f5f5f5. 2. Insert a color fill layer above your two shapes. 3. Change that fill to your base color. 4. Set the blending mode to overlay, and bring the opacity right down to between 5 and 40% (in the example below, it’s set at 40%). 5. Use the color picker and copy your new values. I should point out that this method works exceptionally well when your overlay color is blue. For any other color, you will want to either bring the opacity right down to 5 to 10% or stick with your original grays. Our color scheme is complete.

Applying Your Color Scheme

Now that we’ve got our color scheme, it’s time to apply it. This is a whole other article unto itself. Tip: If you struggle with color, a good trick is to create your website layout in grayscale first. Figure out the hierarchy, and then experiment with the color later. Our accent, red, stands out beautifully against the base color. This is used in very small areas, for buttons and in the icons. The less you use this color, the more it will stand out. The dark gray is used for the text, logo and icon outlines. (Don’t skip putting the colors in your icons. It’s a small detail but makes a big difference.) The white and light gray form the background. The light gray doesn’t have to be here at all, but I find it is another small detail that really makes a website look polished.

Conclusion

As you can see, we really don’t need much more than the palette we’ve created today. But that doesn’t mean you are limited to these colors! As you’re designing, you might decide it’s appropriate to introduce some more colors to your palette. That’s totally fine! As long as you’re attentive, you can use the steps above to find more colors that work with your scheme. The beauty of this is that the more you do it, the better you’ll become at choosing colors. You’ll get to know what works together and what doesn’t. Sometimes, the method above will yield results that are less than desirable, so feel free to tweak things. Play around and have fun learning color theory, without the theory!
Source: https://www.smashingmagazine.com

Mar 30 2016
CSS
Mar 30

Most web developers use CCS on a daily basis – This can be a good thing or a bad thing, depending on the organization of your codebase. Larger projects can be a CSS nightmare when not properly organized.

Good CSS etiquette requires well thought out coding principles, a good foundation and a large selection of tools to make your work easier. Each project, individual or team is different so the resources and tips below may or may not apply to your project but most of them can be incorporated into your workflow.

Coding Principles

Usually before starting your project you need to get together with your team members and decide on why and how you will do things. This will lead to a better and longer lasting CSS codebase. You can do this in different ways and styles, according to your needs and preferences. For example, you can use a text file or Google doc that’s shared between team members. It can also be its own website – it all depends on the scale and importance of your project. It’s a good idea to take a look at GitHub, it might help you get started.

CSS Preprocessors

CSS preprocessors can be a huge benefit to your project, if they are used correctly. Less and Sass are some of the most popular CSS preprocessors available. Preprocessors can be very helpful due to their features: limited nesting, multiple files, mixins and variables. Before implementing or using a CSS pre-processor, ensure that all team members are on the same page.

Starting resources

When working on a greenfield project, it’s a good idea to use Normalize.css. Normalize.css helps browsers to render all elements consistently. You can also check Jonathan Neal’s Sanitize.css. Another useful little resource is Bass.css, which is a collection of utilities and base element styles.

Grids

Generally speaking, sites that start of small will continue to grow bigger over time – without a solid grid foundation in place things can become very complicated very quickly. Hence it’s recommended to have simple or complex grid systems within your CSS which will spare you a lot of work in the long run.

Tools

A good foundation and solid principles is the base to creating good CSS. Let’s take it to the next level by using tools to improve our workflow. The most popular tools nowadays are Gulp and Grunt – each of these tools has a selection of features which we can use to provide feedback, manipulate the code and help enforce rules.

Other useful plugins include:

Recess – Developed by Twitter, it is a simple yet attractive code quality tool for CSS

CSS Lint – As the name states, this plugin helps you lint CSS files

PostCSS – One of the most popular CSS processors, currently used by Shopify, Twitter and Google

Page Speed Insights – You can run desktop and mobile performance tests for your site with reporting to help you with building the website.

Gulp and Grunt offer plenty of plugins that not only help your CSS but other aspects of your project as well – it’s highly recommended to spend time and familiarize yourself with these two.

Performance is very important for any online project, so you should definitely check out these tools and speed up your website: SpeedCurve, WebPageTest and Calibre.

The EditorConfig plugin is great when you’re working on a codebase with other developers. This little plugin aligns the coding standards set out by the team leader and ensures everyone is on the right track.

Conclusions

Experience always helps when creating CSS but keep in mind that nothing will ever be perfect. Keep analysing your code in order to ensure proper results and if you ever get stuck simply ask a friend for help.

Feb 16 2016
CSS
Feb 16

The concept is simple: you can use more complex CSS files that could contain variables, functions, “mixins” and other things, too. These files would be compiled after development into normal CSS files supported by all the web browsers out there. First, you would ask yourself: “Why should I use a more complex CSS, if the old and simple CSS works just fine?”. The main answer for this question is quite simple: because it simplifies your work, you will write less. For a more detailed answer, I will write some reasons why a preprocessor is better: - regular CSS is a very simple language: you have selectors for targeting elements and you style these elements with different properties; yes, this would make the language more friendly for amateurs and designers (even if they don’t have experience with computer programming), but this forces you to do things the long way - with CSS preprocessing you can start using variables and functions, this will allow you to reuse parts of your code over and over again - you wouldn’t repeat yourself anymore CSS example: .simple { font-size: 20px; font-weight: 600; line-height: 1.3em; text-transform: capitalize; } .simple-red { font-size: 20px; font-weight: 600; line-height: 1.3em; text-transform: capitalize; color: red; } .simple-blue { font-size: 20px; font-weight: 600; line-height: 1.3em; text-transform: capitalize; color: blue; } The same code using Less: .simple { font-size: 20px; font-weight: 600; line-height: 1.3em; text-transform: capitalize; } .simple-red { .simple; color: red; } .simple-blue { .simple; color: blue; } - as you can see, nothing is repeated, that means you will save a lot of time and you can use this time for other things - you will update your code easier (besides the fact that you don’t need to remember some things) For example, you can define variables for colors like this: $red: #FF0000; $blue: #0000FF; After that, you can use them for different elements, for example: h1 { color: $red; } h2 { color: $blue; } If you decide that $blue is not ok and you want to change it, you only modify it once at the beginning and it will work for all your code. - your CSS code will be more organized, both LESS and SASS support nested definitions; for example: Normal CSS: p { color: red; font-size: 15px; font-weight: 600; } p span { color: blue; font-size: 16px; font-weight: 300; } p span:hover { color: #FFF; text-decoration: underline; } Using a preprocessor: p { color: red; font-size: 15px; font-weight: 600; span { color: blue; font-size: 16px; font-weight: 300; &:hover { color: #FFF; text-decoration: underline; } } } - it’s easy to use; for example, for SASS you would write a simple command line to watch for your SASS files and compile them automatically if you would modify anything - you will spend more time to make your website prettier (using the time you saved) - it’s easy to use, you will learn it faster than you think - you can use frameworks, the most popular one, Compass, automatically generates vendor-specific CSS properties and has lots of useful functions

Jan 05 2016
Jan 05

We’ve been thinking about code reviews lately here at Advomatic.  Fellow Advo-teammate Oliver’s previous post covered the whys of our code review process, and Sarah covered the hows when she did a overview of some tools we use regularly.  This post focuses on the front-end side, and deals more with the whats of front-end code review… as in:

  • what are our main overall goals of the code we write?
  • what are the common standards we follow?
  • and what quick-and-easy changes can we make to improve our front-end code?

Guiding Front-end Coding Principles

In the world of front-end development, it seems like there is an intimidating, constantly expanding/changing set of tools and techniques to consider.  The good news is that there is a pretty dependable set of widely accepted working guidelines that aren’t tool-specific.  We really try to consider those guidelines first when we are reviewing a peer’s code (and the technical approach they have taken):

  • Write valid, semantic HTML5 markup – and as little markup as needed
  • Enforce separation of content, functionality/behavior, and presentation
  • The site should function without the use of JavaScript, which when added, is only used to progressively enhance the site. Visitors without JavaScript should not be crippled from using the site.

Best Practices

Sometimes there are a million ways to solve a single problem, but I think we do a good job of not pushing a particular tool or way of dealing any of those problems.  Instead, we’ll see if the code is efficient and if it can stand up to questions about its implementation, as far as best practices go.  For example:

  • Is there logic-related PHP in templates that should be moved to template.php?
  • Can JS be loaded conditionally from a custom module or the theme’s template.php via
    $render['#attached']['js']
    

    so it doesn’t load on pages that don’t need it?

  • Is the project already using a DRY CSS methodology elsewhere?  BEM or SMACSS maybe?  Should it be used here?
  • Are we generally following coding standards?
  • Are we coding with web accessibility guidelines in mind?

Minimal Effort Refactoring or “Grabbing the Low Hanging Fruit”

Refactoring code as an afterthought (or as a reaction to some problem down the road), is never fun – it pays to be proactive.  Ideally, we should always be retooling and improving our code as we go along as we get more information about the scope of a project and if the project budget and/or timeline allows for it.  When we look at a peer’s code changes, what kinds of things can we suggest as a quick and easy “upgrade” to their code?

  • Markup:
    • Instead of that ugly Drupal-default markup we’re working with, can it be swapped out with an appropriate HTML5 replacement element?
    • Is that inline JS or CSS I see in the markup?  Crikey, what’s that doing here?!?
    • Do we really need all these wrapper divs?
    • Is this the bare minimum markup we need?
  • CSS/Sass:
    • Can we use an already-established Sass mixin or extend instead of duplicating styles?
    • Is this element styling worthy of a new mixin or extend that can be reused on other elements, either now or in the future?
    • Should this mixin actually be an extend (or vice versa)?
    • If the code is deeply nested, can we utilize our CSS methodology to make the selector shorter, more general, or more concise?
    • Is this selector too unique and specific?  Can it be generalized?
  • JS:
    • Does this work without JS?
    • Is there a chance this could adversely affect something unrelated?
    • Does it need to be more specific, or be within a Drupal behavior?
    • In Drupal behaviors, do selected portions of the DOM use the “context” variable when they should? For example:
      $('#menu', context)
      
    • Is jQuery Once being used to make sure that code is only run once?
    • Should this code only run when we are within a certain viewport size range (a breakpoint)?
    • Does it need to be killed/destroyed when the breakpoint changes?
    • Would this functionality benefit from being fired via feature detection, especially if our target browsers are old-ish?

Quick Browser QA

I know, I know.  Browser QA is not really “code review”.  However, it does go hand in hand, and makes sense to deal with when you’re reviewing someone’s code.  It is at that point that you, the code reviewer, are most familiar with your peer’s work and specific goals.

While we do a more thorough and complete test and review of work in target browsers and devices at the end of an iteration (generally every two weeks), we also do a shorter burst of quick QA during an individual ticket’s code review.  We’ll quickly check it in the latest version of major target browsers/devices – this helps us find bugs and issues that are big, visible and easy to fix.  It also ensures that they don’t pile up on us to deal with during our final iteration… which can be really demoralizing.

Back to Basics

Code reviews are great for brushing up on the basics when other parts of your work can seem very complicated.  None of this is particularly revolutionary – it helps to revisit the basics of why you do what you do from time to time. Aside from reviewing the technical aspect of the work, you can act as an outsider that can see the big picture of how this work affects the user experience… easier than someone in the trenches.  This is an important and valuable role to play as things come together on the front-end of your project.

Oct 20 2014
Oct 20

Recently 10 members of the Drupal development team at Capgemini went to Drupalcon Amsterdam. Having been to two Drupalcons before, I more or less knew what to expect, but something I hadn’t previously given much thought to was how big an event it is. Compared to most other web conferences, it’s a beast. For me personally, I wonder if it’s getting too big and too impersonal, and I think that I’ll be more interested in going to smaller events.

Some of the more interesting sessions for me were the BoFs - in particular a discussion of open source training material and apprenticeships provided a lot of food for thought, and hopefully we can get involved at some level. Capgemini already does a lot of work getting graduates and apprentices into our engineering practice, and with such a big Drupal team, I hope we can benefit from and contribute to the Open Drupal initiative in 2015.

Whenever I go to an event, I come back with a to-do list, and this was no exception. I’ll definitely be digging further into CasperJS following Chris Ruppel’s session on Automated Frontend Testing. I was also very interested to hear about the way that Lullabot spin up test environments for pull requests - it will be good to investigate the feasibility of incorporating this into our workflow.

The other talk that stood out for me was John Albin Wilkins on Styleguide-Driven Development. For a long time, I’ve had a bee in my bonnet about the value of component libraries over Photoshop comps, and it was good to be reminded that I’m not alone. In an interesting session, John outlined an approach to integrating component-based design and automated style guides to agile development projects.

It’s been said many times before, but it’s worth remembering that all too often, people are still thinking in terms of pages, rather than systems.

In the context of the work that we do, this is even more important. We’re a large development team, building CMS-driven sites for large corporate clients, where the design is done by a team working for another company. We’ve made some inroads into building a more collaborative process, but it’s still too easy to end up with the designers throwing things over the wall to the developers. Very often the designer isn’t closely involved during the build phase, and design tweaks are agreed between the client and the developer without the opportunity to go back to get the designer’s opinion.

This is the whole point of living style guides - component libraries that stay in sync with the code as it evolves. As Shay Howe has discussed, component libraries help everyone on the project.

Designers are reminded of the visual language of the project, and it’s easier for them to see when they’re about to reinvent the wheel.

Style guides help developers by defining and documenting standards, and make it easier to dig in and find the way you solved some problem six months ago.

The projects we work on are large and complex, with a long lifecycle, and as developers we need to value maintainability of the front end code. Part of John’s approach to this was his class-naming convention. Having seen Jonathan Snook present on SMACSS I’d thought it was interesting, but to a certain extent it felt like a fancy name for something that was basically common sense. John’s presentation brought the concept to life well, and persuaded me that there’s more to it than that, with an impressive display of flower power.

The other interesting aspect was splitting up SASS files into components, and using KSS to create the style guide - this is something I definitely intend to do on my next project.

Modularity makes sense - it’s how the back-end is going, it’s how Javascript is going, so why shouldn’t design and CSS go the same way?

UPDATED 3rd December 2014: Unfortunately we got Chris Ruppel’s name wrong in the original version of this post, calling him “Dave Rupl”. Sorry Chris.

May 14 2013
May 14

Jack, my co-themer here at Advomatic, and I will be doing a series of articles about how we use SASS and Compass on our projects. There are plenty of articles out there on what it is and how to get started, so we wanted to dig a little deeper, and share a few tips and ideas.

is that IE7 I smell?

Today I'll talk about Modernizr, which is a javascript library that will check to see if your browser supports HTML5 and CSS3 features. We use it on every project now to make sure we aren't serving unsupported stuff to browsers that can't handle it. One thing Modernizr does is add classes to your HTML tag, like "cssgradients" or "no-cssgradients," or "textshadow" or "no-textshadow" as the case may be. Combined with SASS, this can be a very simple way to limit your CSS3 work. Here's an example of how we now apply any of our css3 theming, using the way SASS allows you to check for parent classes, and the nice CSS3 includes of Compass.

h1.title {  // A double border, for browsers that support box shadows; single border for those that don't.
  border-bottom: 1px solid #c3c3bf;
  .boxshadow & {
    @include box-shadow($white 0 1px);
  }
}

Here's a slightly more elaborate example:

#footer {
  background-color #114163: // a baseline background color
  .lt-ie10 & { // dirty proprietary filter for IE9 and below
    filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#2074b1', endColorstr='#114163');
  }
  .cssgradients & { // gradient for CSS3-supporting browsers
    @include background-image(linear-gradient(#2074b1, #114163));
  }
}

By the way, that handy ".lt-ie10" class on the html tag is standard now in Drupal's Zen base theme. It's very handy. While we try to avoid it, we also will add in classes for .mac, .pc, .chrome, .firefox and .safari, if we have some extremely browser-specific problems, which is rare. If you are curious, here's the javascript we use to add that information to the html tag.

Drupal.behaviors.targetBrowsersOS = {
  attach: function (context, settings) {
    // Check to see which operating system we're using.
    if (navigator.appVersion.indexOf("Mac")!=-1) {
      $('html').addClass('mac');
    }
    else {
      $('html').addClass('pc');
    }
    // Check to see if the browser is Safari and doublecheck that it is not Chrome.
    if (navigator.userAgent.indexOf('Chrome') > -1) {
      $('html').addClass('chrome');
    }
    if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {
      $('html').addClass('safari');
    }
    if (navigator.userAgent.indexOf('Firefox') > -1) {
      $('html').addClass('firefox');
    }
    if (navigator.userAgent.indexOf('MSIE') > -1) {
      $('html').addClass('ie');
    }
  }
}

So, as you can imagine, this gives you the ability to customize what css various browsers are served, and leaner, cleaner experience all around. Stay tuned for more SASS/Compass tips and tricks!

Mar 06 2013
Mar 06

Episode Number: 

122

The Drupal 7 Block Class module provides an easy way to add a CSS class to a Drupal block.

In this episode you will learn:

  • How to use the Block Class module to add a CSS class to a Drupal 7 block
  • Cases that having a CSS class on your Drupal block might be useful

Thanks to Drupalize.me for sponsoring this episode of the Daily Dose of Drupal.

DDoD Video: 

Feb 18 2013
Feb 18

Episode Number: 

110

The Drupal 7 Style Guide module is a very simple module that helps you when building a Drupal theme. The module provides a single page displaying how your Drupal theme renders common Drupal elements, form elements, and other HTML elements. By having all of these elements rendered in one page, it makes it much easier to ensure your theme covers all the basics.

In this episode you will learn:

  • How the Drupal Style Guide module will help you build better Drupal themes
  • How the Style Guide module helps make sure you don't forget to theme any common Drupal and HTML elements

Thanks to Drupalize.me for sponsoring this episode.

DDoD Video: 

Feb 05 2013
Feb 05

Episode Number: 

102

The Drupal 7 @font-your-face module is one of the easiest ways to get started with adding web fonts to your Drupal 7 website. It provides an easy to use administrative interface which makes adding web fonts simply point and click.

In this episode you will learn:

  • How to download and configure the @font-your-face module
  • How to use Google Fonts API with the Font your face module
  • How to use a custom CSS selectore with the @font-your-face module
  • How to add the Font your Face code directly to a Drupal theme

Today's episode is sponsored by Drupalize.me

DDoD Video: 

Jan 15 2013
Jan 15

Over 4 years ago, Alan Burke noticed that Drupal didn't have any CSS coding standards. He asked the documentation team lead at the time, Addison Berry, for advice and she suggested that if they wrote the first draft of the CSS coding standards, that would get the ball rolling on discussing them. The goal being to write, iterate and come to consensus on Drupal’s coding standards. See http://groups.drupal.org/node/14421 for the original discussion.

Unfortunately, its 4 years later and the CSS coding standards are still marked “Draft”. http://drupal.org/node/302199

Fortunately, there are now some great external resources for CSS coding standards. I've taken Drupal’s former draft and combined it with other resources, added a sprinkling of new Drupal 8 features and come up with a new expanded DRAFT version of our CSS standards:

So that we can actually move from DRAFT to consensus, I'd like to timebox this discussion to 2 weeks today. All comments should be in by January 30, 2013! Hopefully, by then we'll have reached consensus on most items. Any item that we haven't reached consensus on should be removed from the standard.

Speak up!

Nov 12 2012
Nov 12

How to Hide Metadata From Showing on a Published Drupal Page

Drupal's FieldAPI gives site builders a wide variety of ways to attach custom data to content types and other entities. Sometimes, though, you're adding metadata -- stuff that shouldn't be displayed directly when a piece of content is shown, but can affect the content's relationships with other posts, or its overall appearance. The easiest way to do this yourself is to hide the field in question, then sneak extra CSS classes or IDs onto the node itself based on the field's value. A new module, Field Formatter CSS Class, automates that process and makes turning simple fields into extra CSS classes a no-brainer.

Screenshot of administration screen

As one might guess from its name, the module adds a new FieldAPI Formatter type -- "CSS Class." When selected, the field in question doesn't appear in the visible content of the node or entity in question. Instead, the field's value is turned into a CSS class and added to the entity's wrapper div. This is most useful when combined with a List field or a Text field with a small number of allowed values. When combined with some simple CSS rules in a custom theme (or added via a module like CSS Injector), this allows content editors to make easy choices that affect a node's visual appearance without hacking complex markup or embedded CSS rules into the content itself.

Screenshot of resulting change to site

Field Formatter CSS Class is also smart enough to sanitize the CSS classes that it adds -- even if you allow editors to enter custom text in a field, dangerous HTML attributes and CSS tricks will be scrubbed out. If you need a quick and simple way for editors to pass information about a node or other entity to the theme, Field Formatter CSS Class is a solution worth checking out!

*/
Jul 17 2012
rmo
Jul 17

Hello, Shadow is here!

Posted on: Tuesday, July 17th 2012 by Richard Mo

Have you ever felt that doing front-end web development for mobile web devices (i.e. Android, iOS) is a real pain, especially when you can’t do any inspections quickly? Designers or Themers would totally agree with me on this. Web developers, in general, would feel the same way but not as much as designers/themers do. And how about QA in general – manually pressing links or refreshing pages? It’s a lengthy process… Now, may I suggest to you that it is possible to shadow your actions across multiple devices?

I’ve recently been introduced to Adobe Shadow which addresses all the pain I mentioned earlier. A quote from Adobe Labs:

“Adobe® Shadow is a new inspection and preview tool that allows front-end web developers and designers to work faster and more efficiently by streamlining the preview process, making it easier to customize websites for mobile devices.”

Basically, it allows you to sync all URL changes to every shadowed device and inspect HTML and CSS on each and every one of them.

Here are some features Adobe® Shadow provides:

  • Synchronized Browsing and Refreshing (Device Pairing) — Wirelessly pair multiple iOS and Android devices to your computer.
  • Remote Inspection —Target a device for remote inspection and using familiar development tools, make changes to your HTML, CSS and JavaScript and see your device update instantly.
  • URL Monitoring — Shadow monitors the Address Bar in Chrome, and sends updates to Shadow devices as they happen.

Setting the system up isn’t hard at all; there are, however, 3 things you must download to get things up and running:

  1. You need to download the Adobe® Shadow service which installs onto your desktop. It acts as a server then communicates with all your devices.
  2. Download and install the Chrome browser extension which you would use to control your Shadow devices.
  3. Finally, each device (Android or iOS) must install their respective Shadow app.

Combining all 3 pieces of the puzzle, hook them up, and there you go!

Adobe® Shadow is excellent for traditional websites, where every page is uniquely named (i.e. each page has a unique URL), because Shadow devices follow URL paths sent by the host and interact with the native browser. Most AJAX elements on the page, however, will not be compatible with Shadow for that reason. Web applications built purely using JavaScript, Sproutcore per se, will not work.

Then, what would Adobe® Shadow be used for? Drupal! Shadow is excellent for Drupal front-end development! It really speeds things up for designers and themers. The built-in HTML CSS inspector will let you see what’s going on with each device and you can take screenshots for all of them at once!

For further information, please visit Adobe Shadow.

May 14 2012
May 14

This is a guest post from Adam, my Co-founder at BEgINr Media

When finished: After you get through this tutorial you will have made a custom Quicktabs style in Drupal 6.

This is how to do it.

Stuff I am assuming:
...you have downloaded the Quicktabs module from Drupal.org and Install it.
...you have a photo editor (Gimp, Photoshop, etc)

  1. If you choose you can build Quicktabs from scratch. This would mean building your own CSS and files. I am to lazy for this, so for this tutorial we are going to take a lot of the code and images from an existing tab style. To get started I took a copy of the Garland tab style and pulled it down to my local machine (just copy the files and paste them somewhere you can easily get to them).
  2. Take the Garland folder and give it an unique name. This will end up being the name that you select in the tab style drop-down. Also, while you are renaming things make sure to change the garland.css file to something unique as well. Note: if you site does not need right to left display you can delete this css file.
  3. Open up your newly named css file in a code editor. Once you open this file you will notice that the css is still using the old tab style theme of Garland. To fix this simply replace “garland” with the name of your css file. So for example if you named your css file “quicktabs.css” you would substitute “garland” with “quicktabs”.
  4. Before we start to edit the images and css this is a good time to check and make sure your new tab style code is getting read. To check this simply go to the admin section for quicktabs and in the tabstyle drop down change the style to your newly created style (http://yoursite.com/admin/build/quicktabs). Note: if you see the same style has the one you copied the css and images from your code is getting read correctly. If you see nothing make sure that you have changed the css file to look for your new tab style (Garland -> Quicktabs).
  5. Open up your photo editor and grab the images that you would like to change. For this example, I am going to edit both the left and right tab images. Note: this is a horizontal Quicktabs so I have no need for the sidebar images and the sidebar code in the css. If you would prefer you can delete these from your folder. In addition to the tab left and tab right, I also am going to create two additional images to display for the non-active tabs.
  6. To get the active tabs to work, all you have to do is upload your new designs to the server. If you changed image sizes, you will have to adjust some CSS to get the images to fit properly. Getting the in-active tabs to work is also very easy. Within the code you will find the css that is getting called for the current active tab. Simply copy that and paste that before the active selectors. Once that is done all you have to do is remove the .active class and change the background images to reflect the inactive images. Remember the right image is attached to the li selector while the left image is attached to the a selector.
  7. The remaining changes for the Quicktabs are only minor. These include font-sizes, colors, margins, etc. I have provided the full code below if you are curious of the changes.

If you happen to be a more visual learner here is the CSS and images that I used to create my quicktabs style.

.quicktabs_main.quicktabs-style-spl_quicktabs {
  width: 517px;
}
 
ul.quicktabs_tabs.quicktabs-style-spl_quicktabs {
  font:bold 12px/20px Arial;
  padding: 3px 0;
  height: 20px;
  margin:0;
}
 
ul.quicktabs_tabs.quicktabs-style-spl_quicktabs li {
  margin:0;
  padding:0;
  display: block;
  float: left;
  padding: 2px 0 1px !important;
  list-style-type: none;
  background: none;
}
  ul.quicktabs_tabs.quicktabs-style-spl_quicktabs li:first-child {
    margin-left: 0;
  }
 
ul.quicktabs_tabs.quicktabs-style-spl_quicktabs li a:link,
ul.quicktabs_tabs.quicktabs-style-spl_quicktabs li a:visited {
  color: #fff;
  padding: 8px 40px 4px 40px;
  margin:0;
  font:bold 12px/20px Arial;
}
  ul.quicktabs_tabs.quicktabs-style-spl_quicktabs li.first {
    background: url("./images/tab-q-fixed.gif") no-repeat left -23px;
    width: 168px;   margin-right: 1px;
  }
    ul.quicktabs_tabs.quicktabs-style-spl_quicktabs li.first.active {
      background: url("./images/tab-q-fixed.gif") no-repeat left top;
    }
  ul.quicktabs_tabs.quicktabs-style-spl_quicktabs li {
  width: 194px;
  background: url("./images/tab-info-fixed.gif") no-repeat left -23px;
  }
    ul.quicktabs_tabs.quicktabs-style-spl_quicktabs li.active {
      background: url("./images/tab-info-fixed.gif") no-repeat left top;
    }
  ul.quicktabs_tabs.quicktabs-style-spl_quicktabs li.last {
    background: url("./images/tab-ship-fixed.gif") no-repeat left -23px;
    width: 153px;   margin-left: 1px;
  }
    ul.quicktabs_tabs.quicktabs-style-spl_quicktabs li.last.active {
      background: url("./images/tab-ship-fixed.gif") no-repeat left top;
    }
ul.quicktabs_tabs.quicktabs-style-spl_quicktabs li.active a  {
  color: #585858 !important;
}
 
/* IE 6 Debug */
* html ul.quicktabs_tabs.quicktabs-style-spl_quicktabs,
* html .sidebar ul.quicktabs_tabs.quicktabs-style-spl_quicktabs {
  padding-bottom: 0px;
}
 
/* IE 7 Debug */
*+html .sidebar ul.quicktabs_tabs.quicktabs-style-spl_quicktabs li a:link {
  padding-bottom: 4px;
}
Apr 23 2012
Apr 23

Posted Apr 23, 2012 // 7 comments

Let’s face it – data is invaluable, integrations are key, and generating that information into something that will show up on a person’s browser (often) thousands of miles away in a matter of seconds is a modern miracle. However, if your site isn’t aesthetically appealing, nobody will stick around to see all the good stuff. This is where Cascading Style Sheets (CSS) come into play, and why tools such as LESS that make CSS easier to develop and revise have seen widespread adoption in web development.

CSS is an incredibly powerful tool, allowing web developers and designers to alter the entire look and feel of a website with a few simple style rules. Something as simple as: 

a, a:link, a:visited {
  text-decoration: none;
  color: red;
  font-style: italic;
}

can change the appearance of every link (the “A” tag) on every page of your site. Although very powerful and flexible, some aspects of writing CSS become redundant and hard to re-use such as colors, backgrounds, and dimensions. This is where CSS preprocessors such as LESS come to your rescue.  

LESS is More

LESS was born out of perceived shortcomings of the SASS project, and provides more options for developers to implement. LESS can be set up using a Node.js server to generate new CSS files from LESS files as they are changed. You can also include a LESS JavaScript library that will effect just-in-time compilation of LESS code on the browser. Another option available in CMS environments such as Drupal and WordPress are plugins that compile LESS code on the fly on the server so there is neither a slowdown on a user’s browser nor a need to configure a Node.js installation (which is not for the faint of heart). On to some contrived examples to demonstrate what LESS brings to the table.

Variables

For example, you want to modify the style used on several elements, but the design calls for the same color to be used in several places that don’t lend themselves to leveraging pure CSS to use the same color, as in this example where a color is used for text in one rule and the background in the other:

h1.title {
  font-size: 1.5em;
  color: #339966;
}
...
h2.title {
  font-weight: bold;
  padding: 10px;
  background: #339966;
  color: white;
}

Now if you decide that the shade of green shown above needs to be changed everywhere in the site, you have to search and replace all properties in all stylesheets with pure CSS, making sure you don’t accidentally change the color where it might still need to be used. With LESS, you can declare a variable to use like this:

@title-color: #339966;

h1.title {
  font-size: 1.5em;
  color: @title-color;
}
h2.title {
  font-weight: bold;
  padding: 10px;
  background: @title-color;
  color: white;
}

Nesting

The LESS syntax also allows for more logical grouping of CSS rules. Say for instance you had markup for a listing that had CSS like the following:

#list {
  margin: 20px 0;
}
#list .list-item {
  color: black;
}
#list .list-item.odd {
  background: #eee;
}
#list .list-item .list-item-title {
  font-size : 1.25em;
  font-weight: bold;
}
#list .list-item .list-item-content {
  font-size: 0.75em;
  margin: 0 0 0 20px;
}

This same CSS rules could be written using LESS as:

#list {
  margin: 20px 0;
  .list-item {
    color: black;
    &.odd {
      background: #eee;
    }
    .list-item-title {
      font-size : 1.25em;
      font-weight: bold;
    }
    .list-item-title {
      font-size: 0.75em;
      margin: 0 0 0 20px;
    }
  }
}

Notice how child items can logically be nested, and the selectors don’t require the parents to be specified once nested. Multiple classes and pseudo-classes can even be treated as child selector elements that modify a main class using the “&” notation. 

Mixins

Yet another powerful feature available in LESS is the concept of “mixins” which allow you to re-use CSS “fragments” in multiple rules, including parameterized values (example borrowed from the LESS site):

.rounded-corners (@radius: 5px) {
  border-radius: @radius;
  -webkit-border-radius: @radius;
  -moz-border-radius: @radius;
}

#header {
  .rounded-corners;
}
#footer {
  .rounded-corners(10px);
}

Where the CSS fragment declared for class “.rounded-corners” is re-usable in the header and footer declarations with different corner radii. 

Functions & Operators

LESS also allows for functions and operations to be applied to various CSS attributes such as dimensions and colors, which are entirely too detailed to get into in this intro. Suffice to say there are numerous examples and a full function reference available on the LESS site.

In summary, if you are looking for a more logical and flexible way to build CSS, look into LESS. It extends CSS in a logical way that allows legacy CSS to still work as always, but allow developers and designers a way to organize CSS in a way that makes more sense and gives more options for modifying rules and values en masse with either the server or browser.

References

As a Senior Developer at Phase2, Robert Bates is able to pursue his interests in solving complex multi-tier integration challenges with elegant solutions. He has experience not only in traditional web programming languages such as PHP and ...

Jan 20 2012
Jan 20

Quick Mobile Device Detections

Posted on: Friday, January 20th 2012 by Justin Tsang

Here are a few ways to detect if the user is coming from a mobile device. Used for redirection, different interfaces, or special cases.

Javascript:

PROS: Most common solution.
CONS: Many mobile devices don't support Javascript or users turn it off.

<script>
  var isMobile = navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/);
</script>

Use CSS @media handheld or screensize

PRO: Way to display certain CSS styles for mobile devices.
CON: Many Cellphones don't support the handheld media type, they display their pages with the screen media type by mistake.

<style>
  @media handheld{ .icon { display: none; } }

  @media only screen and (max-width: 999px) {
    /* rules that only apply for canvases narrower than 1000px */
  }

  @media only screen and (device-width: 768px) and (orientation: landscape) {
    /* rules for iPad in landscape orientation */
  }

  @media only screen and (min-device-width: 320px) and (max-device-width: 480px) {
    /* iPhone, Android rules here */
  }
</style>

Use PHP or your coding language of choice

PROS: Does not rely on script language or CSS being supported by phone.
CON: Lots and lots of other potential user-agents that are used by mobile devices may popup in the future. The code will catch some of them but not all later on.

There is a Google project that shows the specific code which is downloadable here: http://code.google.com/p/php-mobile-detect/

$is_mobile = $detect->isMobile();

WURFL (Wireless Universal Resource File)

The last resort is WURFL which is a software component which contains the descriptions of thousands of mobile devices. It is basically an XML configuration file plus a set of progamming APIs to access the data. For more documentation on how to implement it please read:
http://wurfl.sourceforge.net/help_doc.php

Nov 25 2011
ben
Nov 25

The layout of Antiques Near Me (a startup I co-founded) has long been built using the sturdy 960.gs grid system (implemented in Drupal 6 using the Clean base theme). Grids are very helpful: They allow layouts to be created quickly; they allow elements to be fit into layouts easily; they keep dimensions consistent; they look clean. But they have a major drawback that always bothered me: the grid-X classes that determine an element's width are in the HTML. That mixes up markup/content and layout/style, which should ideally be completely separated between the HTML and CSS.

The rigidity of an in-markup grid becomes especially apparent when trying to implement "responsive" design principles. I'm not a designer, but the basic idea of responsive design for the web, as I understand it, is that a site's layout should adapt automagically to the device it's viewed in. For a nice mobile experience, for example, rather than create a separate mobile site - which I always thought was a poor use of resources, duplicating the content-generating backend - the same HTML can be used with @media queries in the CSS to make the layout look "native".

(I've put together some useful links on Responsive Design and @media queries using Delicious. The best implementation of a responsive layout that I've seen is on the site of FourKitchens.)

Besides the 960 grid, I was using LessCSS to generate my styles: it supports variables, mix-ins, nested styles, etc; it generally makes stylesheet coding much more intuitive. So for a while the thought simmered, why not move the static 960 grid into Less (using mixins), and apply the equivalent of grid-X classes directly in the CSS? Then I read this article in Smashing on The Semantic Grid System, which prescribed pretty much the same thing - using Less with a library called Semantic.gs - and I realized it was time to actually make it happen.

To make the transition, I forked semantic.gs and made some modifications: I added .alpha and .omega mixins (to cancel out side margins); for nested styles, I ditched semantic.gs's .row() approach (which seems to be buggy anyway) and created a .nested-column mixin instead. I added clear:both to the .clearfix mixin (seemed to make sense, though maybe there was a reason it wasn't already in).

To maintain the 960.gs dimensions and classes (as an intermediary step), I made a transitional-960gs.less stylesheet with these rules: @columns: 16; @column-width: 40; @gutter-width: 20;. Then I made equivalents of the .grid_X classes (as Clean's implementation had them) with an s_ prefix:

.s_container, .s_container_16 {
  margin-left: auto;
  margin-right: auto;
  width: @total-width;
  .clearfix();
}
.s_grid_1 {
  .column(1);
}
.s_grid_2 {
  .column(2);
}
...
.s_grid_16 {
  .column(16);
}

The s_grid_X classes were purely transitional: they allowed me to do a search-and-replace from grid_ to s_grid_ and remove the 960.gs stylesheet, before migrating all the styles into semantic equivalents. Once that was done, the s_grid_ classes could be removed.

960.gs and semantic.gs also implement their columns a little differently, one with padding and the other with margins, so what was actually a 1000px-wide layout with 960.gs became a 960px layout with semantic.gs. To compensate for this, I made a wrapper mixin applied to all the top-level wrappers:

.wide-wrapper {
  .s_container;
  padding-right: 20px;
  padding-left: 20px;
  .clearfix();
}

With the groundwork laid, I went through all the grid_/s_grid_ classes in use and replaced them with purely in-CSS semantic mixins. So if a block had a grid class before, now it only had a semantic ID or class, with the grid mixins applied to that selector.

Once the primary layout was replicated, I could make it "respond" to @media queries, using a responsive.less sheet. For example:

/* iPad in portrait, or any screen below 1000px */
@media only screen and (max-device-width: 1024px) and (orientation: portrait), screen and (max-width: 999px) {
  ...
}
 
/* very narrow browser, or iPhone -- note that <1000px styles above will apply here too! 
note: iPhone in portrait is 320px wide, in landscape is 480px wide */
@media only screen and (max-device-width: 480px), only screen and (-webkit-min-device-pixel-ratio: 2), screen and (max-width: 499px) {
  ...
}
 
/* iPhone - portrait */
@media only screen and (max-device-width: 480px) and (max-width: 320px) {
  ...
}

Some vitals tools for the process:

  • Less.app (for Mac), or even better, the new CodeKit by the same author compiles and minifies the Less files instantly, so the HTML can refer to normal CSS files.
  • The iOS Simulator (part of XCode) and Android Emulator (with the Android SDK), to simulate how your responsive styles work on different devices. (Getting these set up is a project in itself).
  • To understand what various screen dimensions looked like, I added a simple viewport debugger to show the screen size in the corner of the page (written as a Drupal6/jQuery document-ready "behavior"; fills a #viewport-size element put separately in the template):
    Drupal.behaviors.viewportSize = function() {
      if (!$('#viewport-size').size()) return;
     
      Drupal.fillViewportSize = function() {
        $('#viewport-size').text( $(window).width() + 'x' + $(window).height() )
          .css('top', $('#admin-menu').height());
      };
      Drupal.fillViewportSize();
      $(window).bind('resize', function(event){
        Drupal.fillViewportSize();
      });  
    };

After three days of work, the layout is now entirely semantic, and the 960.gs stylesheet is gone. On a wide-screen monitor it looks exactly the same as before, but it now adapts to narrower screen sizes (you can see this by shrinking the window's width), and has special styles for iPad and iPhone (portrait and landscape), and was confirmed to work on a popular Android tablet. It'll be a continuing work in progress, but the experience is now much better on small devices, and the groundwork is laid for future tweaks or redesigns.

There are some downsides to this approach worth considering:

  • Mobile devices still load the full CSS and HTML needed for the "desktop" layout, even if not all the elements are shown. This is a problem for performance.
  • The stylesheets are enormous with all the mixins, compounding the previous issue. I haven't examined in depth how much of a problem this actually is, but I'll need to at some point.
  • The contents of the page can only change as much as the stylesheets allow. The order of elements can't change (unless their visible order can be manipulated with CSS floats).

To mitigate these and modify the actual content on mobile devices - to reduce the performance overhead, load smaller images, or put less HTML on the page - would probably require backend modifications that detect the user agent (perhaps using Browscap). I've been avoiding that approach until now, but with most of the work done on the CSS side, a hybrid backend solution is probably the next logical step. (For the images, Responsive Images could also help on the client side.)

See the new layout at work, and my links on responsive design. I'm curious to hear what other people do to solve these issues.

Added: It appears the javascript analog to media queries is media query lists, which are event-able. And here's an approach with media queries and CSS transition events.

Oct 04 2011
Oct 04

We've been hearing a lot about responsive design and the future of the web recently. At DrupalCamp Montreal this September, Jen Simmons and Jake Strawn talked about why responsive design is taking hold. I was inspired to try out some of the techniques they talked about, and decided to convert evolvingweb.ca to be more responsive.

Unlike creating an iPhone app for your website or throwing together a mobile theme, applying responsive design to your existing site requires you to change the design of your website. What I thought would be a few small adjustments to the theme turned into a larger project to make our design and theme more flexible and robust.

What is Responsive Design?

Rather than designing a site that works for one screen size, or designing separate themes that work for different devices, the goal of responsive design is to build a website that adapts to the width of the user's screen and works for both large and small screens. This involves creating a flexible-width layout that will adapt as the screen size changes, and writing some CSS specific to screens with a particular size so that you can trim down or hide certain elements at smaller widths and restrict the width of the page at large screen widths.

Media Queries

Currently, the main technique for implementing responsive design is to use media queries. Media queries allow you to include CSS files based on the size of the user's screen or device. At different screen widths (or device widths), you can load different CSS files which change the layout and styling of the page. You can do this either by targeting screens with a particular minimum width, maximum width, or both.

CSS for Larger Screens

To include CSS files for screens larger than a certain width, you can use the following in your mytheme.info file:

stylesheets[screen and (min-width: 760px)][] = css/screen-760.css
stylesheets[screen and (min-width: 960px)][] = css/screen-960.css

The screen-760.css file is loaded for browsers the width of 760px, but also larger screens. It allows for a total page width of 760px and also defines a layout for the columns to fit in that width.

The screen-960.css file is loaded for any a screen width of 960px or larger. It restricts the width of the page to 960px and allows for normal-sized column widths (i.e. 640px for the main content and 320px for the sidebar). If you're converting an existing theme to be responsive, this will contain a lot of what used to be in your layout CSS file.

CSS for Smaller Screens

Include the following in your .info file to include CSS for screens smaller than a certain width:

stylesheets[screen and (max-width: 320px)][] = css/screen-320.css
stylesheets[screen and (max-width: 480px)][] = css/screen-480.css

The screen-320.css file would only be loaded for screens 320px wide or narrower. The screen-480.css file would be loaded for screens 480px or narrower. Notice that since a device that is 480px wide will load both files, it makes sense to load the screen-480.css file second so it overrides the styles in the 320px stylesheet.

CSS for a Range of Screen Sizes

You can also effectively set a range of screen sizes that your CSS will target by combining a min-width and min-width in your media query.

stylesheets[screen and (min-width: 480px) and (max-width: 760px)][] = css/screen-480-760.css

Inline Media Queries

Depending on your design, you might end up with a lot of screen-size-specific CSS files. Sometimes it's more appropriate to use several media queries within a CSS file, using the @media rule.

@media screen and (max-width: 480px) {
  #page {
      width: 480px;
  }
}

Device Width vs. Browser Width

I should clarify that using min-width means that the CSS file will be loaded based on the browser width, so this will apply to users of large monitors who resize their browser. This is really useful for testing your responsive design, since you don't need to switch devices to see your design change, just change the width of your browser. If you only want to detect the device width only, use min-device-width or max-device-width.

It's Not Working on Android!

In addition to adding these media queries, Android devices need a 'viewport' meta tag to being able to detect their own screen width. Adding the media queries above won't have any effect on Android devices until you add this meta tag to your site. You can add it from your mytheme_preprocess_html() function using drupal_add_html_head() like this:

<?php
  $meta_viewport 
= array(
    
'#type' => 'html_tag',
    
'#tag' => 'meta',
    
'#attributes' => array(
      
'name' => 'viewport',
      
'content' => 'width=device-width'
    
)
  );
  
drupal_add_html_head($meta_viewport'viewport');
?>

What to do about Internet Explorer?

Internet Explorer versions 6-8 don't implement media queries. For these versions of IE, you can either implement some kind of responsive solution with javascript, or you can decide not provide the responsive layout for IE users, which the approach I took. In this case, you still need to provide CSS targeting IE so that users viewing your website on a larger device with IE will not see a full-width design. To implement this approach, the CSS you'll want to add for IE will likely be the same as what you added for screens that have a min-width of 960px (or whatever your widest page layout is). Drupal doesn't allow you to add a CSS file more than once, so you'll have to create a duplicate CSS file. My solution was to create a separate screen-960-ie.css file and use @import to include in it all the CSS from the screen-960.css file.

You can add a CSS file for IE only using the Conditional Stylesheets module. You can also add the file from your template.php file using drupal_add_css() and setting the browsers parameter.

Designing for Mobile

The instructions above will get you started adding media queries to your Drupal theme, but I think there's a lot to be said about how to actually create a 'mobile first' design. As themers, we're not used to designing and writing flexible-width themes for tiny devices. Even though you might like the idea of 'mobile first', your client probably expects you to design for standard-sized monitors and adapt the design for smaller devices afterwards.

Adapting a design to be responsive after it's fleshed out for a fixed-width screen is not an easy task. You can stack columns on top of each other at smaller widths, make certain elements smaller, and remove others altogether, but some elements are going to be hard to adapt. If you resize your browser to a smaller width, you'll notice a lot of awkward layouts (i.e. an image that takes up almost the full width of a column, with just a couple words wrapping to the right of it).

The best approach is to start thinking about how to make your theme responsive as you're designing and building it, and testing it at various screen widths as you go. This is going to be a challenge when the designer and themer are different people, especially if the designer is working exclusively in Illustrator or Photoshop.

Writing CSS for Responsive Design

Here are some tips to get you started writing CSS for responsive design.

  • Watch out for elements that are positioned absolutely. Will they overlap with other items at smaller screen widths?
  • Make sure your horizontal menus items wrap gracefully. Try centering them on smaller screens and using the CSS3 white-space: nowrap property.
  • Check the line-height on text that wraps at smaller screen widths.
  • Set a max-width for images of 100%, as well as for the HTML tag that wraps each image.
  • Set a max-width of 100% for form elements as well.
  • Watch out for elements with a fixed height or width. Try setting a min or max width or height instead.
  • Watch out for elements that are altered with javascript, including slideshows and text replacement tools.
  • Watch out for text that floats next to images. Do you need to change this behaviour for smaller width screens?

What do do with Tables and Panels

I found dealing with tables and Panels to be a huge challenge. Columns could be removed at smaller widths, or stacked on top of each other rather than sitting next to each other.

  • Panels layouts with more than one or two columns will not work well on smaller screens. Try writing CSS to remove columns or float columns differently at smaller widths.
  • If you're using grid-style Views to display non-tabular data, consider another display technique.
  • If you need to display data in a table, consider using advanced CSS techniques as described in this article.
  • Some of your mobile users will have an app for displaying spreadsheets on their device, so consider generating a CSV for users to download if you have a lot of tabular data to display.

Resources

Beyond Responsive Design

For some use cases when mobile performance is a priority, you'll probably want to go beyond responsive design and actually change the markup of the page for different devices. To get started doing this in Drupal, try the Mobile Tools or Context User Agent. However, mobile detection doesn't replace responsive design, and using device detection is probably out-of-scope for most Drupal projects.

Responsive design is really exciting and a great challenge for both designers and themers. While using a base theme that provides a responsive layout is great, it doesn't mean that you don't have to think about responsive design. We need to understand how different screen sizes effect our designs and how to meet the challenge of responsive design by creating more robust and more flexible themes.

Sep 19 2011
Sep 19

Columns. While it may seem like a good idea to a graphic designer, the idea of newspaper-style columns strikes fear in the hearts of themers everywhere. In particular, you may run into an instance where you need a list view to be A-L in the first column, then M-Z in the second column. I'll walk you through a method for doing just that, using a little PHP. Note that this is for Drupal 7, but is easily adaptable for Drupal 6.

I will note first that there are a couple other quickie options that might work for your situation.

1. There are several javascript solutions available, which finds a midpoint in the text and wraps the chunks in divs. This works, but if a user has a plugin like NoScript enabled, this solution does not degrade gracefully.

2. There IS a CSS3 multicolumn solution, but it is largely unsupported. Currently it is only supported by Firefox 1.5+ and Safari 3.

So, eventually, there will be a simple CSS solution, but, for the time being, the cleanest option is server-side, using PHP.

In my example here, we'll look at theming a list view to have multiple columns.

Say you have a view with a some items that we want to display in two columns. Views generates HTML that looks something like this:

<div class="view-columns">
  <div class="view-content">
    <div class="views-row views-row-1 views-row-odd views-row-first"> ... </div>
    <div class="views-row views-row-2 views-row-even"> ... </div>
    <div class="views-row views-row-3 views-row-odd"> ... </div>
    <div class="views-row views-row-4 views-row-even views-row-last"> ... </div>
  </div>
</div>

Here's what that looks like just floating each row to the left. Looks like columns, but they are not in the order we want.

floated rows

Instead, we want something that looks like this:

newspaper style columns

To make this themable with CSS, we need the markup to look like this instead:

<div class="view-columns">
  <div class="view-content" id="leftcol">
    <div class="views-row views-row-1 views-row-odd views-row-first"> ... </div>
    <div class="views-row views-row-2 views-row-even"> ... </div>
  </div>
  <div class="view-content" id="rightcol">
    <div class="views-row views-row-3 views-row-odd"> ... </div>
    <div class="views-row views-row-4 views-row-even views-row-last"> ... </div>
  </div>
</div>

The solution to building this markup is with PHP in a views template. The next trick is to choose the right one! Editing your view, click on the Advanced tab, then on Theme: Information. We want to use the Display output template. So, for example, mine is called: views-view--columns--page.tpl.php.

First, we'll make a preprocess function in our template.php file specific to that views template file that finds the number of view results and the halfway point.

This first function here is a helper function for Drupal 7 so you can add preprocess functions to specific views on the fly:

<?php
 
function THEME_preprocess_views_view(&$vars) {
    if (isset(
$vars['view']->name)) {
     
$function = 'THEME_preprocess_views_view__'.$vars['view']->name;
      if (
function_exists($function)) {
      
$function($vars);
      }
    }
  }
?>

And here's the preprocess function:

<?php
 
function THEME_preprocess_views_view__columns(&$variables) {
   
$view = $variables['view'];
   
// Create a variable that divides number of results in half and add one.
   
$variables['half'] = ceil((count($view->result) / 2) + 1);
  }
?>

Once you have determined the $half variable, which is row number that starts the second column.

So let's add the markup to the views tpl file.

Replace the lines:

<div class="view-content">
  <?php print $rows; ?>
</div>

with:

<?php
 
// remove white space in html
 
$rows = preg_replace('~>\s+<~', '><', $rows);
 
// add the </div><div> in at the halfway point to separate the columns
 
$search = '<div class="views-row views-row-' . $half;
 
$replace = '</div><div id="rightcol" class="view-content"><div class="views-row views-row-' . $half;
 
$rows = str_replace($search, $replace, $rows); //
?>

<div class="view-content" id="leftcol">
  <?php print $rows; ?>
</div>

This will wrap the first half of your results in a leftcol div and the second half in a rightcol div. From there, float your columns and add the necessary padding. Enjoy!

Sep 13 2011
Sep 13

Quick Tip(s): Using CSS to hide button text

Posted on: Tuesday, September 13th 2011 by Sonja Farrell

Just a few quick tips today about using css to hide button or link text. This is especially useful when you can’t form alter to make the .

First of all, make sure to set this rule:

text-align: left;

Otherwise, the indent won’t work!

Also, make sure that these rules are set as well:

white-space: nowrap;
overflow: hidden; (or outline: none;)
text-indent: -9999px;

Since text-indent only indents the first line, you have to make sure that there is no wrapping, especially if the text you are trying to hide is quite long. Overflow: hidden and outline: none stop that weird little dotted selection box from appearing when you click the button or link.

Hope this helps!

P.S. - Make sure your button or link has a meaningful/helpful alt text so that screen readers will still work.

Jul 10 2011
Jul 10

The way Drupal have been handling css styles up until recently have been to say it nice "Problematic" Theres been a lot of unessasey barries for new & experienced frontend developers alike, fiddeling with the css files can even caused functionality to break.
Now in D7 theres a hidden gem in the very core that needs to some spotlight on it: the filenaming rules of drupals css files.
Hopefully this post can help module developers & Themers alike understand the beauty of the new css naming rules, and why its so importent to follow these, now and in the future. But first a run down of what the problems actually are both for the frontend & backend Developer, and why this change is extremely importent for the future of Drupal.

css in Drupal is simply wrong

Drupal core & the contrip modules have a habbit of always including at least one css file to define the styles used by the module so it can
* make fancy javascript thingies (ajax, accordians, sliders etc)
* fix the layout for the administration of the module
* fix the layout for the theme (we need more float left & right style definitions)
* add some design styles like colors, margin, padding, fonts or borders, just as good defaults for the theme
All of this so it works outta the box.

Lets not to forget a favorite re defining a couple of common classname like

.user{background:#900}, .odd{margin:4px}

foo module's foo.css

.foomodule div{border:1px dashed red; margin: 1em; font-size:0.889 em}
.foomodule-fancy-ajaxy-thing-container{display:none}
.anotherclassjustbecausewemightneeditsomeday{background: green}
.block div{border-bottom:2px groove pink}

Now when drupal spits out the final page theres a good amount of css files & styles (Drupal alone comes with XXXX out of the box & then add the contrip modules css files) Chances are that the theme will probably have to overwrite, reset and at least take into consideration all these styles, that drupal is pushing out to the frontend.
This has been a HUGE irritation problem for us who define ourself as frontend developers in drupal for years, and there is actually reasons for that:

separation of logic & presentation

There isnt any file system or namescheme that can tells us if the .foomodulestuff style is essential or not to the modules functionality. This makes its actually easy to destroy modules functionality - if youre a bit to aggressive with the resets, or overwrites the wrong styles.

IE file limitations

The number of css files made IE choke because of its limitations of css files that can be added, so the styling for ie was a complete mess untill "rule35" was effected.
The new release of IE 10, the css file limitation is removed, so this isnt a problem for anyone that uses ie10 (which just leaves us with the ie7, ie8 & ie9 users)
This is offcouse not a problem when the css files are compressed in a live site, but its a "small" annoince in the development of the site (not to mention that we at the same time have to battle ie6 drunk cousin ie7)

Overload

Its really easy to get lost in the amount of styles that a drupal site is carring around, when every module has its own classes + Drupal carries its own good amount of stuff.
and lets not forget the css cascade that can end up beeing so complicated that it can be tempting just to use !importent to whatever you need.

If you think you can just drop a style.css into the theme & then expect it to look the way that its defined in style.css, then you havent worked with Drupal -or you just dont give a rats ass about pixel perfect implementations (and then you probably dont care about having 500 unused styles defined) your gonna use countless hours to reset, overwrite & beat drupal into what you might consider best practice, lets be honest drupal is not actually known for a clean mean styles & markup (much of it based on the fact that Drupal7 still supports IE6)

Take the power back

The way to get the control over Drupals styles is normally one of these 4 methodes:

Revove all $styles

Remove "print $styles;" from html.tpl (was page.tpl in d6)
This will remove every css file that drupal even dreamt about , the problem here is that we also remove the administration elements wont work, jQuery sweetnes wont work etc. To make the site work you need to find the css classes thats needed and add them ind by hand - This is generally a very bad idea & will only cause you problems down the road, new modules thats installed wont work etc. but you got complete control ;)

foad style .info css overwrites

In the themes .info file you can easy exclude a css file just by defining it in css with the same filename as the file you wanna remove.
So lets say you wanna kill off foomodules pesky foomodule.css apparently it adds pink dotted lines around you divs & makes you cry & you basically dont wanna deal with it.

** THEMENAME.info **

stylesheets[all][] = foad/foomodule.css

Now Drupal is tricked into beliving that we have a css files in foad/foomodule.css define in the theme, so it includes that file in the $css list - it dosnt exist so woho its now dead & gone :)
The reason i use the foad as a fake folder is to remember that this file myst Fuck Off And Die.

You should remember though to be carefull what you call the css files in you theme, naming accedentially a file views.css have gotten me into trouble a couple of times. (views-style.css is a much safer name)

Stylestripper module

The stylestripper module to remove all the css files you dont wanna include in a theme. The problem here is that you have to do alot of configuration each time you create a new theme
Guess that features & strongarm can probably do that + havent tried yet in D7.

Overwrite styles as needed.

Offcourse we have the simpel & classic way to clean out is to overwrite & zeroing out the styles thats defined by drupal, and you dont need. Just overwrite all style that drupal spits out, and then you done
This results here is a pretty huge css file thats only job is to zeroing out styles thats been defined & the theme dosnt need.
and you gonna have to fiddel with that file everytime theres new modules added to the site.

These 4 methodes always leaves us down to the simple question:

Why does Drupal add stuff that i dont need, or asked for - thats dumb

(insert you own profanity here)

lets compare this to a database query:

If youre a developer that dont really like to work out in the frontend, let me try to give you an example of how drupals style implementation looks & feels like:
I need the title field from footable so i could do a simple and quick "SELECT title FROM footable" as my database query. - now instead of that just to be sure that i have everything, in case i might one day need it, i better also select the date, the author, the body, its grandmother and what ever i might can find... aaah lets just grap it all
"SELECT * FROM footable"
ah now we have whats needed & offcourse whatever else that might gonna be added to the footable forever.

I can here developers all over the world screaming right now - why oooh why do you wanna select all fields in the table if you only- you are using unessasry resources & it takes longer time to get the data yadi yadi
Well this is how the style css file hell that drupal gives us today feels & its plain wrong.
Everything, including the kitchen sink and its mother are added into the css & spoonfed down the throat of the theme - the frontend development now have to paddel through the ton of styles defined from a ton modules that all are throwing in their idea of what should be in styles... argh (sorry for ranting).

Best of both worlds!

So what that we really need is something like this:

  • must be ready to go outta the box.
    The reason that Modules comes with all the style defined is that it should be usuable when you install it - it dosnt make sense that the theme must write custom css everytime. Sensible defaults would be nice.
  • We dont wanna have unused styles & have to work with a ton of overwrites. It makes the page load slower & makes it weight more
    It makes styling sites a pain & really dosnt make sense to have a remove when nessesary, when we really wanna have an add when nessesary aproach.
  • Modules needs to be able to tell the themes what they should not mess with, so a theme dont accedentially ends up destroing functionality, by overwriting a style or a css file.

Seperation of css logic

Now in Drupal7 all this is taken into consideration, at least if you look at the system module in core (drupal/modules/system/) it is (I danced with joy when i figured this out)
So Lets look at the css files that system is packing

system.admin.css
system.base.css
system.theme.css
system.maintenance.css
system.menus.css
system.messages.css


(i havent included the -rtl version here in the list)

Look there is no system.css file!
Instead all the files have added a description to them after the module name (.base, admin, theme, maintenance, menuse etc)
That actually means that we now can make themes that dont have the problems that I described earlier.

The module is splitting up the normal modulename.css file into 3 different files:

  • modulename.base.css (system.base.css)
    .base.css file is having all the essential style definitions that we needs to make sure the module is working,
  • modulename.admin.css (system.admin.css)
    heres the styles that we need for the adminstration of the module & finally we have the
  • modulename.theme.css (system.theme.css)
    Gives us good defaults for the module.

Holy crap B.A.T.man does this mean that if we remove all the [modulename].theme.css from my themes css files, i dont have to overwrite it & dont screw with the administration interface or the modules functionality?

-drummroll-

YES!

something like this in your template.php will do the trick

<?php
THEMENAME_css_alter
(){
  foreach (
$css as $file => $value) {
    if (
strpos($file, '.theme.css') !== FALSE) {
      unset(
$css[$file]);
    }
  }
}
?>

uuuh gimme gimme

Unfortunately all of Drupal core is not working this way (yet), I hope that we can get all logic in the core styles seperated asap and theres a ton contrip modules to get up to speed, with the way of the system module.

I have started the work of seperating the core css files into the B.A.T. (base, admin, theme) namescheme in the worlds best theme that "fixes evertyhing thats wrong in drupal (tm)": Mothership.

In the mothership, theres also n controller to quickly cleanout the .theme / .base files etc - very handy to remove some of all the clutter. Steal it use it & make it better please :)

If youre a module developer you should really think about splitting up you modules css into BAT css files. The fact that its the right way to do it, system module does it, you will never again have to curse a theme for accedentially removed a style that was essential to your module.
Dont forget there will not be hordes of angry frontend developers in your issuque going "wtf why are ya not following the Guidelines" ;)

I hope this post have put some light on the problems we currently have in an essential part of Drupal frontend development, theres a simple, clean & easy way to fix this problem.

So please wont you be the Module to my Theme?

Mar 02 2011
Mar 02

We’re going to be adding CSS3 features for IE to Bartik, Drupal 7 core theme.

CSS3 for IE in Drupal

This is how it looks in IE 8. Predictably, no CSS 3 goodness.

CSS3 for IE in Drupal

If you want IE to look like modern browsers, there’re several ways to deal with it. Personally, I wanted to find a solution that didn’t involve more javascript or browser hacks. Enter CSS3Pie. The front page has a demo where you can try it out (open the page with IE to see it in action).

CSS3 for IE in Drupal

CSS3Pie is very simple: to trigger it, you need to download PIE.htc file and add just one line to your css properties with the path to the PIE.htc file :

behavior: url(/PIE.htc)

If you use Drupal, you have to cpecify the full path to the file (ex: sites/all/themes/your_theme/PIE.htc).

CSS3 for IE in Drupal

Check the theme, and now it’s working.

To fix the gradients, add the following line:

-pie-background: linear-gradient (color1, color2)

CSS3 for IE in Drupal

Note that sometimes you need to add position relative to the target element or its parent. Consult with the CSS3PIE documentation for possible issues and examples of usage. As usual, don’t forget to clear your cache if you have it turned on and keep in mind that IE can’t load more than 31 stylesheets at a time.

Jan 04 2011
Jan 04

When doing development work, from time to time it is handy to be able to look up documentation. Bookmarking manuals is handy, but often you still need to search for the function you're after. Firefox, and possibly other browsers (not Chrome or Chromium), allows you to setup a keyword bookmark linked to a search.

I've setup a few search bookmarks for development resources. This is how I've done it:

  1. Select Bookmarks > Organise Bookmarks... from the menu.
  2. Right click on the bookmarks menu (or any folder) on the left pane
  3. Select New Bookmark... from the context menu
  4. Drupal bookmark example
    Fill in the information for the bookmark, the import piece is the keyword, that will allow us to search.
  5. Click save and return to the browser

Now when we want to search the Drupal 7 API, we can just type "dapi ",>

Example Drupal API search in location bar

Now we should see the appropriate page from the Drupal API documentation.

Example Drupal API page

The same method can be used for other PHP web app developer resources, here are some which I'm using.

  • I've found Google to be the best resource for getting help with javascript

I could have implemented this using OpenSearch plugins, but that requires changing the search provider everytime I want to look for something. By using keyword bookmarks I just type the keyword and the search term into the location bar.

Feel free to share your keyword bookmarks in the comments.

Dec 30 2010
Dec 30

As a Drupal themers / front end developers, we are always asked to push the envelope of what's possible with design and theming. With Drupal 6, custom block regions are usually added in page.tpl.php which is normally outside of the actual page node content / comments. It would be above, below content or in sidebars typically. Occasionally you have the need to add a block region within a node area. This comes in handy especially if you are using a custom themed node page that uses CCK fields, e.g., "node-[custom_content_type].tpl.php".  To accomplish this there are a few steps involved.

  1. Determine and add code to the node type you will add it to in your theme. It might be simply node.tpl.php or a custom named node as mentioned above.
  2. Add a preproccess node function to your theme's template.php
  3. Add the new region your theme's .info file
  4. Flush your site cache
  5. Test it out either using context or the actual block page assigning an existing or new block to the new block region

How to add a block region to a node page in Drupal 6

First we need to determine the name of the new block region that we are going to add. In this tutorial we will call it "node_message". In the node page you want to add code to determine where in the page you want to add it. This part is just like adding a regular block region to page.tpl.php. In our example node.tpl.php, we will add the new code after the $content and post meta variables. Note that your node or custom node template file may vary but this will give you an idea of what's possible. Here is code near the bottom of node.tpl.php.

  1.   <div class="content">

  2.     <?php print $content ?>

  3.   </div>

  4. <?php if ($links): ?>

  5.     <div class="postmeta"><?php print $links; ?></div>

  6.   <?php endif; ?>

  7. </div> 

We now insert our new "node_message" block code at the end. Note that you could also wrap a custom div class for the new code as well as illustrated in our example. This new block region should not already be in page.tpl.php as you do not want the region to load and process twice so it should be unique to the node.tpl.php level.

  1.   <div class="content">

  2.     <?php print $content ?>

  3.   </div>

  4. <?php if ($links): ?>

  5.     <div class="postmeta"><?php print $links; ?></div>

  6.   <?php endif; ?>

  7. </div> 

  8.  <?php if ($node_message): ?>  

  9.      <div class="node-message"><?php print $node_message; ?></div>

  10. <?php endif; ?>  

Now we need to tell Drupal how to process this new code so we will go ahead and add our preprocess function to our theme's template.php file. Note if your theme does not have this file you can go ahead and create it. If it is a new template file with nothing else added you need to add an opening <?php tag but not a closing one. If you are adding to an existing template.php file with existing code, then it's not necessary to add the opening php tag.

  1. <?php

  2. function my_theme_name_preprocess_node(&$vars, $hook) {

  3.   $vars['node_message'] = theme('blocks', 'node_message');

  4. }

Note above that "my_theme_name" should be the actual name of your theme so you will need to replace that as well as 'node_message' which is the custom name of your block if you decide to change the name.

The next part entails adding the new block region to your theme's .info file. You can do something like this:

  1. regions[node_message] = Node Message

Again take care in the name, it must reflect the actual name of your block, i.e. 'node_message'. Now we are at a point where you can go ahead and clear your site cache and assign or create a new block on the /admin/build/block page. The new custom 'node_message' region should show up on in the regions drop down menu on this page. If you have Drupal's Context module installed, you can also assign your block to the newly created region using that.

An interesting conversation transpired on Twitter after I posted a link to this blog post:

Twitter conversation

Amy Stephen (@AmyStephen) suggested that this tutorial was similar to using {loadmodules positionname} in Joomla & Steve Burge (@alledia) suggested you could use the Drupal module, Insert Block. This method while similar is more of a one off type implementation for single pages.

What this tutorial does is show you programmatically how to add a block within a node that can be leveraged globally. In a way the Insert Block module is more granular where you can literally insert a block between two paragraphs. The method described in this blog post would be ideal for example of having a block on 50 different pages between two specific CCK fields in a custom themed node which you could simply set with one Context instance.

In the screen capture below you can click to enlarge and see an example of a custom block added within a node. I hope this tutorial has been helpful, feel free to comment with any feedback or issues. This tutorial was inspired by a post on drupal.org: http://drupal.org/node/361209

Screen capture, How to add a block region to a node page in Drupal 6 Example of a block region within a custom themed node-[my_custom_content_type].t
Oct 20 2010
Oct 20

Theming Unique Home Page Elements in Drupal 6 with $is_front & PHP

Ask 10 Drupal Themers how they would accomplish a task in Drupal and you just might get 10 different answers. Most likely those 10 different ways of accomplishing the task would all be valid and unique. This concept would apply when theming a home page element in Drupal; there are several different ways of going about this. For example, you could use page-front.tpl.php, Panels, Context, the front page module or custom body classes -- well the list goes on.

Recently we needed to have a different logo on the home page than the rest of the site as it was on a black background unlike the rest of the site which was a white background so the logo needed to be a reversed version. We were already rendering some CSS styles that were unique to the home page using custom CSS body classes but in the case of the logo, our Drupal theme was already rendering the logo with the  print $logo; tag. In the search to have a different logo, we found a module that could do this but it seemed like too much configuration and overhead for what we needed. So we discovered a Drupal theme variable called $is_front. Combing this with an if-then enabled to render the different logo on the home page.

You can see from the code below that we switch logos based on whether or not the page being called is the home page or not using $is_front. The code is in our site's theme page.tpl.php file so you know where to go to add / edit this.

  1. <?php if ($is_front): // switch the logos for front and interior ?>

  2.         <?php if ($logo): //front page logo ?>

  3.                 <div id="logo">

  4.                         <a href="<?php print check_url($front_page); ?>" title="<?php print t('Home'); ?>"><img src="/sites/default/themes/mytheme/images/logo-black.png" alt="<?php print $site_name; ?>" title="<?php print $site_name; ?>" /></a>

  5.                 </div>

  6.         <?php endif; ?>

  7.         <?php else : ?>

  8.         <?php if ($logo): //call the default logo that your drupal theme provides for interior pages ?>

  9.                 <div id="logo">

  10.                         <a href="<?php print check_url($front_page); ?>" title="<?php print t('Home'); ?>"><img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" /></a>

  11.                 </div>

  12.         <?php endif; ?>

  13. <?php endif; //end logo switch ?>

Hopefully this post will help any others encountering this type of need for unique home page elements in Drupal Theming.

Sep 04 2010
Sep 04
Firefox 3 no span Firefox 3 with span Chrome 6 no span Chrome 6 with span IE6 no span IE6 with span IE7 no span IE 7 with span IE 8 no span IE8 with span Opera 10 no span Opera 10 with span (Win) Safari 5 no span (Win) Safari 5 with span

I came across a problem when working on a Drupal user registration form which had to include an accept terms and conditions checkbox. In fact, I came across a couple of problems, but I only had to fix one myself.

At present there are some bugs in Drupal 6 core pertaining to mandatory checkboxes. Luckily, there's a module for that. I was using the handy terms of use module, which works around the mandatory checkbox problems with or without the help of the checkbox_validate module.

One problem remained though - if I submitted the registration form without ticking the mandatory terms of use checkbox, the form validation worked in that it stopped me proceeding, and I saw the You must agree with the Terms of Use to get an account error message at the top of the form, but there was no visual highlighting of the checkbox in question.

A poke around with firebug confirmed that the form API has been cajoled into doing its form_set_error thing, and the checkbox had the error class. However, styling form elements - particularly the different types of inputs - with CSS has always been a bit hit-and-miss. The 2px solid red border that the stylesheets specified should be around the checkbox was nowhere to be seen.

I checked in several other browsers (lots of screenshots included with this post) - it looked like the IEs and Opera were the only browsers which rendered the red border around the checkbox - Firefox, Chrome and Safari did not.

My workaround is to override the theme function for a checkbox, and to wrap checkboxes with the 'error' class in a span which I can then style. In my CSS I also turn off the red border for the checkbox itself, as otherwise you get double borders in the browsers which don't have this problem in the first place:

<?php
function mytheme_checkbox($element) {
  _form_set_class($element, array('form-checkbox'));
  $checkbox = '<input ';
  $checkbox .= 'type="checkbox" ';
  $checkbox .= 'name="'. $element['#name'] .'" ';
  $checkbox .= 'id="'. $element['#id'] .'" ' ;
  $checkbox .= 'value="'. $element['#return_value'] .'" ';
  $checkbox .= $element['#value'] ? ' checked="checked" ' : ' ';
  $checkbox .= drupal_attributes($element['#attributes']) .' />';
 
  if (strpos($element['#attributes']['class'], 'error') !== false) {
    $checkbox = "<span class='checkbox-error'>$checkbox</span>";   
  }
 
  if (!is_null($element['#title'])) {
    $checkbox = '<label class="option" for="'. $element['#id'] .'">'. $checkbox .' '. $element['#title'] .'</label>';
  }
 
  unset($element['#title']);
  return theme('form_element', $element, $checkbox);
}

...and...

/* CSS */
.checkbox-error {
  border: 2px solid red;
}
.form-item .checkbox-error input.error {
  border: none;
}

The results are not visually perfect - the red border on my span doesn't always hug the edges of the checkbox very neatly - particularly in the browsers which don't render the red border around the checkbox, as they tend to be the ones which are rendering shadows or other fancy effects. Anyway the point is there's now something you can hang your hat on CSS-wise, and that actually shows up in all the major browsers.

Aug 19 2010
Aug 19

In this video, I demonstrate how to add CSS Suckerfish Drop Down Menus to an existing Drupal 6 Theme.

NOTE: On an iPad or other mobile device and cannot see this video: try the direct link: 

Mar 29 2010
Mar 29

The following Photoshop tutorial shows how to apply realistic drop shadows to photos. Once satisfied with your result, you can slice your image up and, using CSS rules, apply creative shadows, hence 3d effect, to any image, Drupal block, Drupal box, etc. Similar tutorials are all over the web — well, not exactly, but there are many. However, I had difficulty understanding the best of them. I clarified the whole process for myself, and have decided to dump it here. Lovely photo. Attached is my Photoshop CS2 file.

Here is my tutorial, scanned from an Hilroy loose-leaf.

Just kidding! Although this image sums it up really well, you may not be able to read it. You'll end up with four layers (as shown on the scan), with 'effects' applied to the two top layers.

Let's go through the process step by step.

  1. Create a new document in Photoshop. Any 'ol version of Photoshop will do. You'll either create your new document as transparent or pre-fill it with some color. Does not matter. However, you might want to create it right off in larger proportions than your photo's. To give you some room. Of course, you can fix it all later using Image → Canvas Size (ALT-CTRL-C in Windows). Me, I created a 800 by 600 pixels document with 72 ppi, pre-filled with white.

  2. Go head and open your photo in Photoshop. Then place your photo in your Untitled document. Know how? Select the layer where your photo is — that layer is probably locked, that's fine, then drag it and drop it onto the window of your Untitled document. This will effectively add a new layer to your Untitled document, on which your photo will reside. Now I realize, doin' it on my end, that my photo is not in 72 ppi, so it is way too big. So I delete my new layer, and resize my photo first (in its own document) using Image → Image Size (ALT-CTRL-I in Windows) and setting the Resolution to 72 ppi. Then I reselect the layer and drag & drop it onto my other document. Done.

    I now have 2 layers. I rename my bottom layer to 'background' and my top layer to 'photo'.

  3. Now comes the fun part, in which we'll create the shadow. This shadow will reside on its own layer, and we will *not* use any effect to create it. Go ahead and create a new layer (SHIFT-CTRL-N in Windows), and name that layer 'shadow'.

    Here is our next goal: create a selection that we will fill with black-ness, and we'll start by shaping this selection after our photo's outline. So, go and select the 'photo' layer. Then, go to Select → Load Selection. In the 'Load Selection' dialog that'll pop up, select 'photo Transparency' as 'Channel'. Click OK. You now have a blinking selection surrounding your photo.

    The next goal is to create a path out of this selection. We want to change the shape of our selection. Once we're happy with the shape, we'll turn in into a selection again and fill it with black-ness. So, how do we do it? Press 'M' to use the Marquee tool. Place your cursor over your image, right click, and from the context menu select 'Make Work Path...' (with Tolerance set to 2.0 pixels). You've now created a path out of your selection.

    Tools used to play with the shadow path

    To distort the path, we'll use these tools: the Direct Selection Tool and the Convert Point Tool. Press 'A' to grab the Direct Selection Tool. Select the top left point of your path. You might have to click twice. You'll know that your point is selected when its little square has turned gray — as opposed to the other 3 points along the path. Move that point away from the photo. Use the Convert Point Tool (from your Tools box, just below) to change that 90-degrees corner to one with handlebars. Play with the handlebars using the Direct Selection Tool. To break the connection between the 2 handlebars of a point, you have to select one of the 2 handlebars with the Convert Point Tool. (And there is another way to achieve this, but I forget...) Repeat the procedure for the other 3 points. At the end, you'll end up with something like this:

    Notice on the last screen capture that the bottom left point is selected: it is gray.

    Important: make sure that there is 1 or many sides to your photo where the shadow is hidden, not showing *at all*. Why? Because if you don't do that — and there is a shadow showing all around your image — your photo will look as if it is floating on the page. That ain't too realistic.

    Now we will turn this path into a selection again. Access the 'Paths' panel, and click on the selection icon, shown here:

    We will now fill our selection with black-ness. Make sure that your 'shadow' layer is selected. Then go to Edit → Fill. Select 'Black' from the drop-down. Then deselect all (CTRL-D). Set the Opacity of your 'shadow' layer to ~50%, right now or later. Then, apply a Gaussian blur to your layer. Make sure that when you apply this filter your shadow is no longer selected, because if it's still selected your filter will only apply to your selection, and we want to apply the 'blur' to the entire layer. You'll end up with a layer that looks like this, when others layers are hidden from view:

    We now have 3 layers. Reorder your layers so that the shadow is under the photo.

  4. We will now create our white border. This part is easy. Create a new layer (SHIFT-CTRL-N in Windows), and name that layer 'outline'. We need to create a selection based on the photo outline. We did this before in step 2, but we hadn't saved our selection. Go ahead and select the 'photo' layer. Then, go to Select → Load Selection. In the 'Load Selection' dialog that'll pop up, select 'photo Transparency' as 'Channel'. Click OK. You now have a blinking selection surrounding your photo. Press 'M' to revert to the Marquee tool. Then press the ALT key. Do not move your finger from that key. Placing your cursor above your current selection, you'll see that your cursor has turned into a plus sign with a smaller minus sign next to it. What that means? It means we'll subtract from our current selection. Draw a rectangle selection within your current selection. You're creating a selection in the shape of a border. In the process of creating your border, you'll hide part of your photo, you will effectively crop it. (I wish I'd told you this before, please do not slap me.) Once done, select your 'outline' layer, then go to Edit → Fill, and select White as your fill. Then deselect all (CTRL-D). You have a white outline, border, whatever, on your 'outline' layer.

    We now have 4 layers, like so:

Time to add 2 Photoshop effects

  1. We'll apply a gray-to-white gradient on the white border. Right-click on the 'outline' layer, in your Layers palette, and choose 'Blending Options...' from the context menu. Check 'Gradient Overlay' in the list on the left in the dialog box. Double-click on 'Gradient Overlay' to access the gradient properties. Make sure you play with the Angle. Look at the preview. Decide for yourself where the Light is coming from.

  2. A final touch will consist in applying some light effect on the photo itself. This step is useless if you slice up the resulting image for use in CSS-styling. Right-click on the 'photo' layer, in your Layers palette, and choose 'Blending Options...' from the context menu. Check 'Inner Shadow' in the list on the left in the dialog box. Double-click on 'Inner Shadow' to access the shadow properties. Make sure you play with the Angle here as well. Look at the preview. Decide for yourself where the Light is falling.

Time to slice up the image for CSS-styling

And time to have supper.

AttachmentSizeHitsLast download advancedShadow.psd1.39 MB484 years 37 weeks ago

Last edited by Caroline Schnapp about 3 years ago.

Pages

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web