CSS hack

Last updated

A CSS hack is a coding technique used to hide or show CSS markup depending on the browser, version number, or capabilities. Browsers have different interpretations of CSS behavior and different levels of support for the W3C standards. CSS hacks are sometimes used to achieve consistent layout appearance in multiple browsers that do not have compatible rendering. Most of these hacks do not work in modern versions of the browsers, and other techniques, such as feature support detection, have become more prevalent.

Contents

Types of hacks

Invalid or non-compliant CSS

Due to quirks in the interpretation of CSS by various browsers, most CSS hacks involve writing invalid CSS rules that are interpreted only by specific browsers, or relying on bugs in specific browsers. An example of this is prefixing rules with an underscore (as in _width) to target Internet Explorer 6—other browsers will ignore the line, allowing it to be used to write code specific to one browser.

Similar CSS hacks involve inducing syntax errors like asterisks, missing whitespace, and CSS comments around property names. Additionally, in Internet Explorer 6 and 7, the !important declaration is recognized as such with any string after the exclamation mark, e.g. !ie. [1]

Unsupported CSS

Although newer CSS rules are correct by current standards, they are ignored by older browsers as "invalid". By writing old rules followed by newer rules that cancel out or modify the old ones, it is possible to only activate certain rules on older browsers.

Conditional comments

Prior to version 10, Internet Explorer supported a special comment syntax that would allow blocks of HTML to be read only by specific versions of the browser. These comments are mostly used to provide specific CSS and JavaScript workarounds to older versions of the browser. No other browsers interpreted these comments or offered similar functionality.

The following are examples of the different syntax for these comments.

<head><title>Test</title><linkhref="all_browsers.css"rel="stylesheet"type="text/css"><!--[if IE]> <link href="ie_only.css" rel="stylesheet" type="text/css"> <![endif]--><!--[if lt IE 7]> <link href="ie_6_and_below.css" rel="stylesheet" type="text/css"> <![endif]--><!--[if !lt IE 7]> <![IGNORE[--><![IGNORE[]]><linkhref="recent.css"rel="stylesheet"type="text/css"><!--<![endif]--><linkhref="not_ie.css"rel="stylesheet"type="text/css"><!--<![endif]--></head>

Critics

Hiding code using hacks often leads to pages being incorrectly displayed when browsers are updated. These hacks can lead to unexpected behavior in newer browsers that may interpret them differently than their predecessors. Since Internet Explorer 6 and 7 have fallen out of use, CSS hacks have declined as well. Modern methods of feature targeting are less fragile and error-prone.

Alternatives

Browser prefixes

Each of the most popular browser rendering engines has its own vendor prefix for experimental properties. However, due to the proliferation of these properties in live code, the browser vendors have begun moving away from this practice in favor of feature flags. [2]

List of prefixes

The following are a list of prefixes from various layout engines:

Vendor PrefixIn UseLayout EngineCreated byUsed by
-ah-YesFormatterAntenna HouseAntenna House Formatter
-apple-Yes WebKit Apple Inc. Apple Safari 2.0, Opera Widgets, WebKit-Based Browsers (as legacy prefix)
-atsc- Advanced Television Systems Committee standards
-epub-YesWebKit EPUB Working Group Chromium / Google Chrome, WebKit-Based Browsers
-fx-Yes Sun Microsystems (now acquired by Oracle Corporation) JavaFX applications
-hp- Hewlett-Packard (now HP Inc. and Hewlett Packard Enterprise)
-khtml-Yes / yes KHTML / WebKit KDE KDE Konqueror / Apple Safari 1.1 through Safari 2.0, WebKit-Based Browsers (as a legacy prefix)
-moz-Yes Gecko Mozilla Foundation Gecko-Based Browsers[?], Mozilla Firefox
-ms-Yes Trident / MSHTML Microsoft Corporation Microsoft Internet Explorer
mso-OfficeMicrosoft CorporationMicrosoft Office[?]
-o-Yes Presto Opera Software Opera desktop Browser up to version 12.16, Opera Mini, and Opera Mobile up to version 12.1, Nintendo DS & Nintendo DSi Browser, Nintendo Wii Internet Channel
prince-Yes Prince YesLogic YesLogic Prince
-rim-WebKit BlackBerry Limited RIM Blackberry Browser
-ro-YesMARTHARealObjectsRealObjects PDFreactor
-tc-TallComponentsTallComponents
-wap-YesPresto The WAP Forum Opera Desktop Browser and Opera Mobile, The WAP Forum
-webkit-yesWebKit/Blink Apple Inc. (WebKit)/Google Inc. (Blink)Apple Safari & Safari for iOS (WebKit), Chromium / Google Chrome desktop and mobile (Blink), Opera desktop and mobile from version 14 (Blink), Android browser (Blink), Nokia MeeGo Browser 8.5, Nokia Symbian Browser 7.0 and later (WebKit), Blackberry Browser 6.0 and later (WebKit).
-xv-NoPrestoOpera SoftwareOpera Desktop Browser for Windows 2000/XP

Example

/* Cross-browser css3 linear-gradient */.linear-gradient{/* Gecko browser (Firefox) */background-image:-moz-linear-gradient(top,#D7D0%,#068100%);/* Opera */background-image:-o-linear-gradient(top,#D7D0%,#068100%);/* older Webkit syntax */background-image:-webkit-gradient(linear,lefttop,leftbottom,color-stop(0,#D7D),color-stop(1,#068));/* Webkit (Safari, Chrome, iOS, Android) */background-image:-webkit-linear-gradient(top,#D7D0%,#068100%);/* W3C */background-image:linear-gradient(tobottom,#D7D0%,#068100%);}

Limitation

Vendor prefixes were designed for features that were under development, meaning that the syntax may not even be final. Also, adding a rule for each browser's implementation of a function does not scale well when you want to support many browsers. Consequently, the major browser vendors are moving away from vendor prefixes in favor of other methods such as @supports feature queries.

Feature deletion

JavaScript feature detection

Multiple JavaScript libraries exist to detect what features are available in a particular browser so that CSS rules can be written to target them. Libraries such as Modernizr add classes to the html element, allowing for CSS rules such as .cssgradients.header.

Feature queries

A new feature known as feature queries was introduced in CSS3, allowing the detection of specific functionality within the CSS (without requiring the use of a JavaScript library for feature detection). This new directive can be used to check for the support or lack of support for a specific feature, and checks can be combined with and, or, and not. Obviously, @supports rules will only work on browsers that support @supports.

header{display:block;}@supports(display:flex){header{display:flex;}}

Script polyfills

While JavaScript feature detection and @supports rules can help to target browsers that require fallback functionality, they will not address bugs in specific browsers or enable that advanced functionality. Polyfills, scripts that make behavior consistent across all browsers, can be used to add support for new CSS rules (for example, media queries in IE 8) as well as fix bugs in specific browsers. Since polyfills add or fix functionality in browsers that do not have it, they serve a different purpose than feature queries, but can be used in combination with them.

Related Research Articles

<span class="mw-page-title-main">HTML</span> HyperText Markup Language

HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. It defines the content and structure of web content. It is often assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaScript.

In computer science, a preprocessor is a program that processes its input data to produce output that is used as input in another program. The output is said to be a preprocessed form of the input data, which is often used by some subsequent programs like compilers. The amount and kind of processing done depends on the nature of the preprocessor; some preprocessors are only capable of performing relatively simple textual substitutions and macro expansions, while others have the power of full-fledged programming languages.

An HTML element is a type of HTML document component, one of several types of HTML nodes. The first used version of HTML was written by Tim Berners-Lee in 1993 and there have since been many versions of HTML. The current de facto standard is governed by the industry group WHATWG and is known as the HTML Living Standard.

The data URI scheme is a uniform resource identifier (URI) scheme that provides a way to include data in-line in Web pages as if they were external resources. It is a form of file literal or here document. This technique allows normally separate elements such as images and style sheets to be fetched in a single Hypertext Transfer Protocol (HTTP) request, which may be more efficient than multiple HTTP requests, and used by several browser extensions to package images as well as other multimedia content in a single HTML file for page saving. As of 2024, data URIs are fully supported by all major browsers.

Link prefetching allows web browsers to pre-load resources. This speeds up both the loading and rendering of web pages. Prefetching was first introduced in HTML5.

Haml is a templating system that is designed to avoid writing inline code in a web document and make the HTML cleaner. Haml gives you the flexibility to have some dynamic content in HTML. Similar to other template systems like eRuby, Haml also embeds some code that gets executed during runtime and generates HTML code in order to provide some dynamic content. In order to run Haml code, files need to have a .haml extension. These files are similar to .erb or .eRuby files, which also help embed Ruby code while developing a web application.

Conditional comments are conditional statements interpreted by Microsoft Internet Explorer versions 5 through 9 in HTML source code. They can be used to provide and hide code to and from these versions of Internet Explorer. Conditional comments are not supported in Internet Explorer 10 and 11.

XPath is an expression language designed to support the query or transformation of XML documents. It was defined by the World Wide Web Consortium (W3C) in 1999, and can be used to compute values from the content of an XML document. Support for XPath exists in applications that support XML, such as web browsers, and many programming languages.

<span class="mw-page-title-main">Sass (style sheet language)</span> Stylesheet language

Sass is a preprocessor scripting language that is interpreted or compiled into Cascading Style Sheets (CSS). SassScript is the scripting language itself.

<span class="mw-page-title-main">CSS</span> Style sheet language

Cascading Style Sheets (CSS) is a style sheet language used for specifying the presentation and styling of a document written in a markup language such as HTML or XML. CSS is a cornerstone technology of the World Wide Web, alongside HTML and JavaScript.

<span class="mw-page-title-main">Google Closure Tools</span> JavaScript developer toolkit

Google Closure Tools is a set of tools to help developers build rich web applications with JavaScript. It was developed by Google for use in their web applications such as Gmail, Google Docs and Google Maps. As of 2023, the project had over 230K LOCs not counting the embedded Mozilla Rhino compiler.

XHTML+RDFa is an extended version of the XHTML markup language for supporting RDF through a collection of attributes and processing rules in the form of well-formed XML documents. XHTML+RDFa is one of the techniques used to develop Semantic Web content by embedding rich semantic markup. Version 1.1 of the language is a superset of XHTML 1.1, integrating the attributes according to RDFa Core 1.1. In other words, it is an RDFa support through XHTML Modularization.

<span class="mw-page-title-main">Less (style sheet language)</span> Dynamic stylesheet language

Less is a dynamic preprocessor style sheet language that can be compiled into Cascading Style Sheets (CSS) and run on the client side or server side. Designed by Alexis Sellier, Less is influenced by Sass and has influenced the newer "SCSS" syntax of Sass, which adapted its CSS-like block formatting syntax. Less is an open source project. Its first version was written in Ruby; however, in the later versions, use of Ruby has been deprecated and replaced by JavaScript. The indented syntax of Less is a nested metalanguage, as valid CSS is valid Less code with the same semantics. Less provides the following mechanisms: variables, nesting, mixins, operators and functions; the main difference between Less and other CSS precompilers is that Less allows real-time compilation via less.js by the browser.

The cache manifest in HTML5 was a software storage feature which provided the ability to access a web application even without a network connection. It became part of the W3C Recommendation on 28 October 2014.

<span class="mw-page-title-main">Sencha Touch</span> JavaScript framework

Sencha Touch is a user interface (UI) JavaScript library, or web framework, specifically built for the Mobile Web. It can be used by Web developers to develop user interfaces for mobile web applications that look and feel like native applications on supported mobile devices. It is based on web standards such as HTML5, CSS3 and JavaScript. The goal of Sencha Touch is to facilitate quick and easy development of HTML5 based mobile apps which run on Android, iOS, Windows, Tizen and BlackBerry devices, simultaneously allowing a native look and feel to the apps.

jQuery Mobile is a touch-optimized web framework, specifically a JavaScript library, developed by the jQuery project team. The development focuses on creating a framework compatible with many smartphones and tablet computers, made necessary by the growing but heterogeneous tablet and smartphone market. The jQuery Mobile framework is consistent with other mobile app frameworks and platforms such as PhoneGap, Worklight, etc.

In software development, a polyfill is code that implements a feature of the development environment that does not natively support the feature. Most often, it refers to JavaScript code that implements an HTML5 or CSS web standard, either an established standard on older browsers, or a proposed standard on existing browsers. Polyfills are also used in PHP and Python.

<span class="mw-page-title-main">Stylus (style sheet language)</span> Stylesheet preprocessor language

Stylus is a dynamic stylesheet preprocessor language that is compiled into Cascading Style Sheets (CSS). Its design is influenced by Sass and Less. It is regarded as the fourth most used CSS preprocessor syntax. It was created by TJ Holowaychuk, a former programmer for Node.js and the creator of the Luna language. It is written in JADE and Node.js.

Front-end web development is the development of the graphical user interface of a website through the use of HTML, CSS, and JavaScript so users can view and interact with that website.

<span class="mw-page-title-main">PostCSS</span> Software development tool that uses JavaScript-based plugins to automate routine CSS operations

PostCSS is a software development tool that uses JavaScript-based plugins to automate routine CSS operations. It was designed by Andrey Sitnik with the idea taking its origin in his front-end work for Evil Martians.

References

  1. Paul Irish (15 April 2009). "Browser CSS hacks". www.paulirish.com. Retrieved 8 June 2022.
  2. "Vendor Prefix". Mozilla Developer Network. Retrieved 12 October 2016.