Posts filed under CSS Tips and Tricks

CSS Best Practices and Tips By Toptal Developers

We at Extra Nerds believe that it is important to support folks like us, with similar philosophies, in the industry and, to that end, here’s our first guest blog post by Toptal Developers.    

CSS Best Practices and Tips

This resource contains a collection of best CSS practices and CSS tips provided by our Toptal network members. As such, this page will be updated on a regular basis to include additional information and cover emerging CSS techniques. This is a community driven project, so you are encouraged to contribute as well, and we are counting on your feedback.

Cascading Style Sheets (CSS) can be described as a style sheet language written in a markup language. It is used for defining the look and formatting elements of Web documents such as the layout, colors, and fonts. The CSS specifications are maintained by the World Wide Web Consortium (W3C). Even though every browser supports CSS, there are many inconsistencies in the supported specification version. Some browsers even have their own implementation of the specification and have proprietary (vendor) prefixes. Supporting all modern browsers is a daunting task, not to mention when developers need to support old and legacy browsers. All these problems cause a lot of trouble for developers, and it is hard for them to write CSS code that will render consistently across all browsers. That’s why we want our top CSS developers and engineers to share their knowledge and offer their best tips to achieve those tasks more easily.

How to Improve CSS Performance

There is a lot you can do to ensure good CSS performance and reduce page loading times. Here are some tips and techniques you can start implementing today.

A browser needs to go through every single DOM element to find what it is looking for. Take this example:

.home-page .header-main .nav-main ul 

The browser will begin by looking for every ul element, then every .nav-main inside of a ul, then every .header-main inside of that, and then every .home-page inside of that. Only when the search is done are styles applied. We can be far more efficient than that and write a specific selector, like this:

.nav-list 

Now the browser simply needs to find the .nav-list element and apply the styles to it. We have kept specificity low and avoided unnecessary nesting. Simple, yet efficient.

Naming classes can be tough, but you can use some of the well known tricks for that. For instance, in our .nav-list element, you can use the .component-descendant-descendant naming:

.nav-list-item

The .nav-list-item would be the list item in the navigation. Alternatively, you can use the BEM naming methodology, already covered in our CSS tips.

Another piece of advice for keeping low specificity is to avoid IDs and use classes. The big benefit of using classes is that you can reuse your styles and help keep your style sheets DRY (Don’t Repeat Yourself), which will also reduce the file size.

How to Write Modular CSS Code

Code duplication is one of the most important issues that originate from coding in plain CSS. In order to contest that, preprocessors come with very strong function, mixin or extend implementations. In this tip we are going to introduce @include and @extend, and discuss how they can be used efficiently in SCSS.

Creating Mixins with @include and @mixin

By utilizing the @include implementation, you can create mixin functions with parameters. For example, a display block centered container with max-width could be implemented as follows:

// Create a max-width container
@mixin maxWidthContainer($width : 1024px) {
        display: block;
        max-width: $width;
        margin: 0 auto;
}

The mixin declared above can be called with the following command: @include maxWidthContainer();. Since the default value for a $width parameter is set to 1024px, generated CSS will look like this:

display: block;
max-width: 1024px;
margin: 0 auto;

Extending Classes with @extend

The @extend can be used to share CSS properties from one class to another. For example, the following button style declarations in SCSS:

.button {
        color: black;
        background: white;
        border: 1px solid gray;
}
.button--warning {
        @extend .button;
        color: red;
        background: orange;
}
.button--disabled {
        @extend .button;
        color: white;
        background: gray;
}

Will result in the following CSS:

.button, .button--warning, .button--disabled {
        color: black;
        background: white;
        border: 1px solid gray;
}
.button--warning {
        color: red;
        background: orange;
}
.button--disabled {
        color: white;
        background: gray;
}

Please notice how the button modifiers (.button--warning and .button--disabled) are stacked in the initial declaration of .button.

Efficient Usage of @include and @extend

Mixin declaration is the most useful function that preprocessors have to offer. @include can be used for anything from adding animations to responsive breakpoints. Any piece of code that is repeated multiple times should be applied into a mixin which will effectively make your code more readable and easily maintainable.

On the other hand, @extend has to be used very carefully and sparsely. While initially it seems to pose plenty of advantages, in its use there are a few disadvantages:

  • You can not extend from within a media query
  • It does not accept any parameters

Both @include and @extend are very strong directives which can make CSS development with the aid of preprocessors way more productive as well as fun.

In addition to these CSS topics, the rest of the blog series includes discussions on Using Stylus to Easily Decouple Semantic Markup from CSS Stylesheets; How CSS Namespacing Can Aid Front-End Development; How to Write Maintainable CSS Declarations; How to Customize an HTML File Input; What is a Block, Element, Modifier Approach; and How to Write Consistent CSS.

Posted on September 30, 2015 and filed under CSS Tips and Tricks.

CSS Tips and Tricks: Part 5 of 6

Vertical Content Alignment

In our introductory blog in this CSS series, we demonstrated display;none and its uses. The second installation provided an overview of CSS3, while the third discussed CSS Syntax. The fourth added a few more general tips and tricks to the arsenal, helping readers take full advantage of CSS and each one of its updates. Now, let’s get specific and talk more in depth about vertical content alignment, which can be a challenging element to working with CSS.

Cascading Style Sheets (CSS) are normally used to make a document more presentable where a style sheet language is used so that it defines the look and formatting usually written in markup language. In most cases, you will find that CSS is used to style a variety of web pages as well as user interfaces that are written in HTML, XHTML and any other sort of XML document. You can simply learn some simple CSS tricks that will equip you with necessary CSS skills, thus ensuring that you are successful in producing a quality content page.

There are quite a number of CSS tricks that we can use to keep our websites cool and attractive. These tricks will help you to improve the quality of your web design since they are easy to implement while also being user-friendly. Below are some important tricks that you can use to align your content vertically, in order to ensure that the quality level of your website is high and, ultimately presentable at a glance.

Absolute positioning. One of the most important tricks that we will feature is the absolute positioning CSS trick for content alignment. In your document, you will realize that you have two <div>, one of them will be the container while the other will be the child element which simply refers to the content. You will be required to start with the container element where you will position it to be relative while the child element is positioned to absolute. This will allow you to freely place it across the container thus allowing you to proceed on easily. So that you will achieve aligning it vertically, you can shift the position of the child element from the top in that it lays half way the height of the container. Then pull it up by half of the width of the child element, thus ensuring that your alignment is fantastic.

Use of CSS3 Transform. This Cascading Style Sheet trick has always made it easy for you to put any of your content at the center. For example, if we have similar HTML structures as the preceding method whereby we have one parent and one element having a — 50% from the top. The use of CSS transform will ensure that there is also a translation of — 50%. For more detailed information on CSS3, please refer to our second CSS blog post on that very topic.

Padding. Another CSS trick that we can use to form illusion in vertical alignment is the use of padding. It is a simple step in that will require you to set the top and the bottom part equal to each other. This trick will be effective if you do not adjust your container in a fixed width, but simply set your width to auto.

Use Line Height. The line-height property will be effective if you want to align a text vertically when you have only one line of element within a container. You will be required to set the value of line-height to a value that is nearly the same as that of the container height.

These are some of the surefire CSS tricks that you can use to align your content vertically thus achieving a high-quality web content. Contact Extra Nerds for these tricks and be sure that you will succeed in your next web designing project.

Hopefully you have learned some helpful hints on CSS in this blog series. Stop back next week for our final installation which will help us to understand modern CSS typography and font styling.

Posted on September 11, 2015 and filed under CSS Tips and Tricks.

CSS Tips and Tricks: Part 4 of 6

More CSS Tips and Tricks

Cascading Style Sheets (CSS) came on the scene over 15 years ago and, on a very basic level, changed the way websites looked and acted. This dialect has continued to advance throughout the years and its various updates are intended to engage designers and developers in order to manufacture websites which are beautiful, effective, and increasingly lightweight. In our introductory blog in this CSS series, we demonstrated display:none; and its uses. The second installation provided an overview of CSS3, while the third discussed CSS Syntax. Before we move forward, let’s take a moment to add a few more general tips and tricks to our arsenal, helping you to take full advantage of CSS and each one of its updates.

Use a decent proofreader. You may be a coding master, but two heads are always than one, as they say. Being ready to approve and turn upward codes, the auto-complete element, and syntax highlighting won't just speed up your work, it will allow for more precision in your stylesheets.

Compress wherever possible. Use an effective compression device to cleave off the bytes from your CSS and JavaScript files wherever possible without deleting substance. This ensures that your website remains unencumbered and loads quickly. One approach to decrease undesirable bytes in your CSS files is to erase copy references, conflicts, and comments. Despite the fact that comments, for example, make it easier for someone else to maintain your files, they increase the record size significantly. It's better to just compose your codes and orchestrate them such that your files are promptly comprehensible. Also, store at any point you can in order to enhance loading times and preserve the bandwidth of your website visitors. It’s worth noting that enhanced loading times also improves the search engine optimization (SEO) prospects of a website and drives it up the Google ranks. You can enhance the execution of your website by using just a single stylesheet that slashes the quantity of HTTP requests.

Increase the meaningfulness of your stylesheets. You can do this in a number of ways, but the simplest is to include white spaces. While this technique will inevitably increase the size of your CSS files slightly, you can ensure that the intelligibility will also enhance manifold times. Make sure that you keep the code format consistent. Another nifty way to ease the maintenance of your stylesheet is to eliminate inline codes. Also, keep the CSS record names simple so that you know at a glance the contents of each document.

Disable CSS to investigate. All browsers have assembled debuggers. Take in the hot keys to initiate these tools. In any case, if you can't spot the glitch even after cautious scrutiny, verify that you disable CSS or evacuate every one of the styles before bringing them back, each one in turn, to simulate the glitch.

Check your codes on all the significant browsers. This is likely the simplest of all CSS tips and yet so many programmers tend to ignore it. Try not to use a browser emulator to check code. Rather, check your codes on the genuine browser or a virtualized version. And don’t forget to keep an eye on all the major browsers - Firefox, Chrome, Internet Explorer, Opera, and Safari.

The aforementioned five CSS tips and tricks should, in a perfect world, be strictly adhered to as best practices as they make easier the lives of developers, website administrators, Google spiders, and website visitors.

Hopefully you’re finding these tips and tricks helpful and we’ll have some more for you next week in our fifth installation of this six-part series. While we touched on vertical content alignment in our CSS3 blog, we’re going to delve deeper into that conversation in next week , so stop back and check it out.

Posted on September 4, 2015 and filed under CSS Tips and Tricks.

CSS Tips and Tricks: Part 3 of 6

The Benefits of Using CSS Syntax for Web Design

In the first blog in this series we talked about display:none:, what it does, why it's useful, and how to use it. And then we followed that up with an outline of CSS3. Now we want to talk about CSS Syntax.

Those who are in the initial stages of creating a website for their business tend to be concerned with how to best utilize both their funds and their time. Luckily, there is a wonderfully effective method of web design that will enable a person to save their money and conserve their time. This is the relatively still unknown CSS
Syntax and, in what seems like the blink of an eye, it is becoming a highly popular and incredibly effective choice for the ultimate objective of economic and user-friendly web design. The overall benefits are simply fantastic and that is what so many web designers, and visitors of the websites which use it, love about it.

So, What Exactly is CSS Syntax?

CSS is becoming widely known as a language which is incorporated to provide the essential detail of a given website’s markup language, HTML or XHTML. The function of HTML is to enable fonts, the website’s complete layout and the various colors and tones integrated throughout. One particular benefit which is it produces is a separation of the varied content within the document. The content itself is almost always written in HTML format or a markup language which is considered similar.

Reliable Flexibility. When you utilize CSS Syntax, changes and alterations to your website can be done in a breeze regardless of the number of pages on which the changes need to be made. The larger the website, the more a person will automatically see how effective and undeniably efficient CSS Syntax is for web design. Another great aspect is that it will ensure that all of the other pages will receive the same changes as directed, at the same time, consistently.

Reduces Bandwidth. When CSS Syntax separates the content of the website from the language used to produce the website’s design, a user will immediately see the great reduction in the size of the file transfer. The document will then be properly stored externally and, at that point, it will be accessed for every single visit from then on. By reducing the amount of bandwidth used, it will free up extra space for a quicker loading time, which could very well play a role in saving money for the user.

Enables Efficiency for the Search Engines. The special technique that CSS Syntax uses is called “clean coding” and what this means is that the various search engines which offer an individual’s website won’t have any issues reading the content. Plus, CSS Syntax will keep from allowing more of the content as opposed to the code because everybody is well aware of how vital the content is to the overall success of a webpage.

Wonderfully compatible with the Browser. Even though compatibility with websites and the browser are progressing every day, CSS Syntax will be able to induce more compatibility between the user’s website and the browser itself. This will help visitors in viewing a website the exact way that the web designer intended it to be viewed.

Regardless of the fact that it is still considered relatively unknown, CSS Syntax and the production value that it brings to users is truly astounding. So much so that its unknown status is bound to quickly change and, soon enough, it will be the number one source for benefiting great web design to its maximum potential. Next week we’ll highlight some additional CSS tricks and tips so stay tuned!

Posted on August 28, 2015 and filed under CSS Tips and Tricks.

CSS Tips and Tricks: Part 2 of 6

What is CSS3?

rsz_1csstipsandtricks2-1.png

Disclaimer: This series of CSS Tips and Tricks will assume you have at least an intermediate level understanding of HTML and CSS.

In the first installation, we outlined display:none; - what it is, why to use it, and how to use it. Next, we’re going to talk about Cascading Style Sheets 3 (CSS3).

CSS3 is a wonderful computer language that can be used to give a better shape to your website. Though the CSS3 language is not terribly complicated, certain new advanced features can be confusing. If you’re not familiar with said features then you may find CSS3 a bit difficult, but let’s see if we can help. If you would like to be a CSS3 specialist or even if you just want to be more familiar with it, here are some tips that can help you to reach your goal.

How centering in CSS can help you to understand CSS3 transformation. Some people find it difficult to deal with centering items in CSS. In fact, they cannot track the centering problem of a web design. This is a very simple procedure and one can easily track this with a little help. Usually, designers try to use perfect positioning so that the elements will be rightly centered, but if you want to choose vertical centering, it’s better to go for CSS3 transform.

Container drive is required for providing an absolute position. However, vertical centering can also be achieved by auto-adjusting through the use of CSS3 transform. You just need to follow some procedures:

                          Go to the div. container, keeping the position relative

                          then go to the div container p, keeping the margin 0

                          make the position absolute, keeping the top 50 %

                          and then go for CSS3 transform

This works exceptionally well for animation since CSS transform is able to apply several visual effects to the elements such as rotate, move, and skew, among others.

Get acquainted with CSS3 specificity. Not everyone is acquainted with the word specificity. This is a basic idea and anyone who wants to be a CSS3 expert must need to be acquainted with this word. Specificity makes the browser choose the appropriate property values to an element and gets them applied through the browser. But the problem of the specificity is that it limits CSS rules to some elements only.

To resolve the problem, you just need to know some specificity rules. For example, ID selectors contain more specificity than attributive selectors. Rules getting more specific selectors will enjoy greater specificity, and override previous and conflicting rules. If you’re still facing specificity problems, then make sure that you are not using the important declaration button and give more effort to use fewer selectors for styling an element and place your style in LVHA order.

Prefer HSL over RGB. Most of the people choose the old RGB hex tag system for the specification of the colors. In the first impression, it looks good as it is specified with different colors like black, red, and blue separately. This RGB system is fine if you’re not working with color controls that require complementary and contrasting shades with similar saturations. In that situation, you'll want to choose HSL in order to get several conversions. And the process will be easy since CSS3 supports HSL color specificity.

Hopefully this has provided a little help to anyone who wants to start using CSS3. Stop back next week for a discussion on the benefits of using CSS syntax for web design.

Posted on August 21, 2015 and filed under CSS Tips and Tricks.

CSS Tips and Tricks: Part 1 of 6

display:none;

Disclaimer: This series of CSS Tips and Tricks will assume you have at least an intermediate level understanding of HTML and CSS.

HTML websites we start to wonder, is there any way I can spice up this bland world of boxes? Can I make my boxes not be boxes? Is there any way to make my text hot pink and my pages’ background sky blue?! So hopefully that last one has never been a motivator for you to learn how to code Cascading Style Sheets (CSS), but you get the picture. In our journey through styling web pages we come across the display attribute. This attribute has been the cause of many headaches, as well as many breakthroughs in terms of styling web pages. There are some pitfalls any web designer and/or developer should be weary of when using this CSS attribute. Consider the following three things to always keep in mind:

What does “display:none;” do?
I will keep this brief, but just so we have some context I felt I should give a little description of what the display attribute can do. According to w3schools.com, “Setting the display property of an element only changes how the element is displayed, NOT what kind of element it is.” Pretty intuitive. There are many values the display attribute can use, but the most common are probably the following: “inline”, “inline-block”, “block”, or “none”. Changing an HTML element’s display attribute to anything different to what that element’s native display value is will change how it affects the overall layout of your pages. Consider an HTML div element. By default, it is a block-level element, but if you set its display attribute to “inline” it will now collapse to only consume as much space as is needed to fit its content. If we then set that same div’s display property to none, POOF! It now appears to be gone. The space it occupied becomes vacant and other elements will (most likely) fill the void of where the div once occupied. However, under the hood in the raw HTML the div is still reallythere, it is just set to “display:none;”

Why am I using “display:none;”?
This is another very important question when considering to use “display:none;”. In answering this question you can determine if “display:none” is the correct solution to “hiding” the HTML content in question. There are three things to consider when using “display:none” which are: space, load speed, and SEO. Let’s consider the first:

Space
This is probably the most familiar consideration most people find the correct solution to, but again, I wanted to mention it. If you want to hide content, but still allow it to take its space within the web page then you want to use a different CSS attribute, “visibility:hidden;”. This will hide the HTML element (and all of its children) but still allow it to take its given space on the web page. However, “display:none;” will completely remove the HTML element (and all of it’s children) from the web page’s rendered layout. Now, let’s consider two other points.

So you may say to yourself, “Yes, I want it completely gone from the rendered web page’s layout.” This raises two things I would like you to consider before slapping a “display:none;” on your HTML element.

Load Speeds
Do you have any other CSS rules (such as a “:hover” pseudo-class) or JavaScript functionality that exists on the web page which will allow the end-user of your website to ever make the HTML element in question seeable? If not, why are you even loading it on the page in the first place? If the content inside of the HTML element is dynamic (maybe some kind of custom query you do on the backend to render this element’s content) then you are putting an unnecessary added load time on your end-user. By putting a “display:none;” on this HTML element you only affect it once your end-user has downloaded it and its content. See what I mean? There is no reason why to even load the content first – save your end-user some load time and just remove the mark-up or backend code that produces it in the first place.

SEO and Screen Readers
So you say to yourself, “Yes, I have functionality which allows the display:none; content to be shown via an onclick event in my JavaScript code.” That’s fine and dandy! There are many, many places where this is completely acceptable. However, you should consider howimportant the content is which is initially loaded on the page with a “display:none;” on it. Although there is some debate as to whether Google’s web ranking algorithm cares about hidden content (and in reality Google search ranking is all anyone cares about), there is good reason to suspect Google either completely ignores “display:none;” content (that is, initially loaded “display:none” elements and their content on your webpage) or gives the content low priority in there search ranking (reference:https://support.google.com/webmasters/answer/66353). The same is true for many screen readers on the market today – many will not even read content that is hidden with a “display:none;”. If you decide the content is important and you would like to rest assured that the content is getting seen by Google and screen readers there are two reasonable solutions.

1) Use this CSS class (thanks to http://css-tricks.com/places-its-tempting-to-use-display-none-but-dont/ – I have modified the class slightly from the cited article but it accomplishes what it is intended to) for the HTML element instead so you can achieve the “same” result as a “display:none;” but still have your content crawled by Google (as well as have eReaders read the content):

.hideElement{

position: absolute;

top:-9999px;

left:-9999px;
overflow: hidden;
clip: rect(0 0 0 0);
height: 1px;

width: 1px;

padding: 0;

margin:0;

border: 0;

}


2) The other way to fix this is to have JavaScript hide the element with a “display:none;” once the page loads. This will ensure that Google sees the content, however, I’m not sure about screen readers (if you are concerned about screen readers just go with option 1). The only downfall of this method is that it relies on JavaScript to drive content, and what if your user has JavaScript disabled? This is a rare encounter, but it does happen. I advise just using the class above for content you want to to completely hide but still have it seen by Google and screen readers.

Warning: Don’t be a wise guy and keyword/content spam with these methods – Google will roast you.

More reading on this topic:

http://css-tricks.com/places-its-tempting-to-use-display-none-but-dont/

http://webdesign.about.com/od/css/f/blfaqhidden.htm

http://alistapart.com/article/now-you-see-me


Posted on January 15, 2015 and filed under CSS Tips and Tricks.