<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>kabayview.com</title>
	<atom:link href="http://www.kabayview.com/feed" rel="self" type="application/rss+xml" />
	<link>http://www.kabayview.com</link>
	<description>A Web Design &#38; Development Reference Archive</description>
	<lastBuildDate>Tue, 17 Apr 2012 15:17:52 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>HTML5 Semantics: New Elements to Replace Div</title>
		<link>http://www.kabayview.com/html5/html5-semantics-new-elements-to-replace-div</link>
		<comments>http://www.kabayview.com/html5/html5-semantics-new-elements-to-replace-div#comments</comments>
		<pubDate>Tue, 17 Apr 2012 15:10:35 +0000</pubDate>
		<dc:creator>Lynda Damiata</dc:creator>
				<category><![CDATA[HTML5]]></category>

		<guid isPermaLink="false">http://www.kabayview.com/?p=1235</guid>
		<description><![CDATA[Written by Edward Korcheg, blog.templatemonster.com:: Perfect semantics was and will always be the Golden Fleece for web developers. HTML5 has come a long way to become a “messiah” that gives hope for a better future to HTML technology. This language has indisputably evolved unveiling 30 new elements that brought semantics to higher level. New tags <a href='http://www.kabayview.com/html5/html5-semantics-new-elements-to-replace-div'> [read more]</a>]]></description>
			<content:encoded><![CDATA[<p>Written by <a title="Edward Korcheg" href="http://www.templatemonster.com/" rel="external">Edward Korcheg</a><a href="http://blog.templatemonster.com/" target="_blank">,<br />
blog.templatemonster.com</a>::</p>
<p><img class="alignleft size-full wp-image-1236" title="HTML5-semantics" src="http://www.kabayview.com/wp-content/uploads/2012/04/HTML5-semantics.jpg" alt="" width="150" height="150" />Perfect semantics was and will always be the Golden Fleece for web developers. HTML5 has come a long way to become a “messiah” that gives hope for a better future to HTML technology. This language has indisputably evolved unveiling 30 new elements that brought semantics to higher level. New tags were developed to help us create more semantic structure. As you may know, the previous version of this Hyper Text Markup Language – HTML4 has the universal tag <strong>div</strong> which was widely used to complete various tasks in the HTML structure. This HTML veteran has one important drawback – unskilled users get lost in a code difficulty as it often looks like a wild <strong>div</strong> mosaic.</p>
<p>With the release of new HTML5 tags, such as <strong>article</strong>, <strong>section</strong>, <strong>header</strong>, <strong>footer</strong>, <strong>nav</strong> and <strong>figure</strong>, many web developers decided that these elements are meant to fully replace our old buddy <strong>div</strong>. This point of view is not quite right, and it’s too early to retire the <strong>div</strong> tag. This tag remain to be a fully functional element of the fifth generation of HTML. According to W3C, the <strong>div</strong> tag defines a division or a section in an HTML document and it can be used to group block-elements and format them with CSS.</p>
<p>Almost 20 new HTML5 elements were created to be used in Document outline, which is the structure of a document including headings, form titles, table titles and other. Today we want to make things clear and tell you about the most popular HTML5 tags that can be used in the Document outline alternatively to the <strong>div</strong> element. Once again we want to pay your attention that these elements cannot be called <strong>div</strong>-killers, they only partially replace the usage of <strong>div</strong> in the markup code, as you can still use the <strong>div</strong> element while coding new page. Here’s a short guide to help you use HTML5 new semantic elements.</p>
<h3>Article and Section</h3>
<p>Tag <strong>article</strong> is an independent fragment of the content. Blog post, news article or other types of text content clearly illustrate the right area to use tag <strong>article</strong>. Basically, you can use this element to markup the page component which is meant to be widely used and distributed.</p>
<p>Tag <strong>section</strong> is the most misleading element that is widely deployed by web developers as an alternative to <strong>div</strong>. You should know that this tag is tightly connected with <strong>article</strong> and is used for grouping content that differs from other content groupings on the page. The example of a chapter in a book is the perfect one to illustrate the main function of a <strong>section</strong>. In other words, this element is used for making several thematically different areas on a single page or for making logical chapters in the articles.</p>
<h3>Header and Footer</h3>
<p>The element <strong>header</strong> was created for a more semantic presentation of navigation tools and other important data placed in the header of the web page. You can use this element as many times as you want by adding some additional tags like <strong>nav</strong> to add some navigation menu elements, headings, tables of contents and other things. Tag <strong>footer</strong> is similar to <strong>header</strong> and it is used to create the footer for the content structure placed above. You can also use this element multiple times on one page for various blocks. This tag can be used not only for marking up classical “footer” of the web page with all required information about Copyright, Terms of Use and the like, but also for marking up some information about the author of the article, for example.</p>
<h3>Nav</h3>
<p>This element is used to create navigation menus with links that allow you to navigate through the page and website. Although, not all the links on the web page must be wrapped with the <strong>nav</strong> element. You can have, for example, a block with Sponsored links or links with the search results. Don’t forget that <strong>nav</strong> element can be also used for multiple times. Often this tag helps mark up unordered list of links and ordered ones with our old buddies <strong>ul</strong> and <strong>li</strong>.</p>
<h3>Figure and Figcaption</h3>
<p>According to W3C reference, the current element is used to present a block of content with a caption, which is typically referenced as a single unit from the main flow of the document. In other words, you can use it to mark up various media types of content like illustrations, photos, code examples and diagrams.</p>
<h3>Aside</h3>
<p><strong>Aside</strong> element is used for secondary content when not nested within an <strong>article</strong> element. The most appropriate example of using <strong>aside</strong> element is the typography insert. We can use this element for <strong>nav</strong> elements, typographic inserts, advertising banners and simply for content that must be placed separately from the primary content.</p>
<p>* * *</p>
<p>There’s no doubt that all those new elements featured above will make you think twice before using the <strong>div</strong> tag. Well yes, they are all super-cool and add way more semantic value to your code than <strong>div</strong> does. But don’t forget that officially the <strong>div</strong> element remains in the HTML5 team and you can always use it if you can’t find any other tag. We believe it’s a wise decision not to forget about this tag due to its versatility and long-term flexibility. So, code wisely, enjoy superb HTML5 semantic code and don’t forget to smile more often.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.kabayview.com/html5/html5-semantics-new-elements-to-replace-div/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Drop Caps: Historical Use And Current Best Practices With CSS</title>
		<link>http://www.kabayview.com/typography/drop-caps-historical-use-and-current-best-practices-with-css</link>
		<comments>http://www.kabayview.com/typography/drop-caps-historical-use-and-current-best-practices-with-css#comments</comments>
		<pubDate>Fri, 13 Apr 2012 15:29:03 +0000</pubDate>
		<dc:creator>Lynda Damiata</dc:creator>
				<category><![CDATA[Typography]]></category>

		<guid isPermaLink="false">http://www.kabayview.com/?p=1203</guid>
		<description><![CDATA[By Laura Franz, April 3, 2012 smashingmagazine.com :: The practice of using a large letter to mark the start of a text has been around for almost two thousand years. Illustrated caps increased usability by marking important passages and guiding readers through the text. Unlike their historic counterparts, drop caps on the Web don’t add <a href='http://www.kabayview.com/typography/drop-caps-historical-use-and-current-best-practices-with-css'> [read more]</a>]]></description>
			<content:encoded><![CDATA[<p>By <a title="Posts by Laura Franz" href="http://www.smashingmagazine.com/author/laura-franz/?rel=author" rel="author" target="_blank">Laura Franz</a>,<br />
April 3, 2012<br />
<a href="http://smashingmagazine.com/" target="_blank">smashingmagazine.com</a> ::</p>
<p>The practice of using a large letter to mark the start of a text has been around for almost two thousand years. Illustrated caps increased usability by marking important passages and guiding readers through the text. Unlike their historic counterparts, drop caps on the Web don’t add value in terms of usability or readability—and they are hard for Web developers to control, often rendering differently across browsers.</p>
<p>Yet, front-end designers and clients often want to use drop caps as decorative elements. How should we implement them? Just as scribes, artisans, and early printers had a variety of methods for creating initial capitals, we Web designers have multiple methods to choose from. We can use an image of a letter, create a class to enlarge and place a letter, or use a first-child:first-letter to enlarge and place the first letter of the first paragraph. But which method should we use? Which method remains consistent across browsers? Which is most accessible?</p>
<div id="textadtarget">
<div id="textad">[<strong>Note</strong>: Have you already pre-ordered your copy of our <a href="http://auslieferung.commindo-media-ressourcen.de/www/delivery/ck.php?oaparams=2__bannerid=3452__zoneid=68__OXLCA=1__cb=f97f57068f__oadest=http%3A%2F%2Fwww.smashingmagazine.com%2F2012%2F02%2F15%2Fsmashing-book-3-preorder%2F%3Fpk_campaign%3Dvvk">Printed Smashing Book #3</a>? The book is a professional guide on how to redesign websites and it also introduces a whole new mindset for progressive Web design, written by experts for you.]</p>
<div id="beacon_f97f57068f"><img src="http://auslieferung.commindo-media-ressourcen.de/www/delivery/lg.php?bannerid=3452&amp;campaignid=1018&amp;zoneid=68&amp;loc=1&amp;referer=http%3A%2F%2Fwww.smashingmagazine.com%2F2012%2F04%2F03%2Fdrop-caps-historical-use-and-current-best-practices%2F&amp;cb=f97f57068f" alt="" /></div>
</div>
</div>
<h3>Initial Caps In Manuscripts</h3>
<p>Examples of initial caps have been found dating back to the 4<sup>th</sup> century CE. Early <em>codex</em> books (books with pages, as opposed to scrolls) did not have word spaces, sentence breaks, or paragraph breaks. The written word was not “read” the way it is now. Written text represented sounds; sounds held meaning. “Readers” lived in a primarily oral culture and verbalized the sounds to help them remember ideas and information already committed to memory.</p>
<p>Historically, initial caps were not just decorative elements. Scribes used them to mark where a new section—a new idea—started in the text. This in turn helped “readers” find their place in a text.</p>
<p>Even as late as the 15<sup>th</sup> century, monks and scribes used initial caps to aid in visually “chunking” texts. Figure 1 shows a <em>manuscript</em> (lettered by hand) bible from 1407. The initial cap (<em>P</em> in the word <em>Petrus</em>) contains a picture of St. Peter, and is thus <em>historiated</em>; it relates to the text by showing a recognizable figure or scene. It is also <em>illuminated</em>; it is decorated with gold in order to bring the light of God to the reader.</p>
<p><em>Historiated</em> caps not only helped mark the start of a new idea in the text, they acted as place markers for significant places in the text. Images related to the story served as memory aids for priests and monks who “read” the texts by flickering candle light.</p>
<p>But look closely (Figures 1 and 2) and you’ll see a far more subtle “initial cap.” The manuscript contains word spaces but does not contain a space between sentences. Thus, the letterer added strokes of red to the first letter of each sentence, giving visual separation to sounds represented on the page.</p>
<div id="attachment_1204" class="wp-caption aligncenter" style="width: 510px"><img class="size-full wp-image-1204" title="dropcap1_illuminated1" src="http://www.kabayview.com/wp-content/uploads/2012/04/dropcap1_illuminated1.jpg" alt="" width="500" height="330" /><p class="wp-caption-text">Figure 1: Illuminated, Historiated Cap in a Latin Bible, 1407. Lettering by Gerard Brils, Belgium. (Image: Adrian Pingstone)</p></div>
<p>&nbsp;</p>
<div id="attachment_1205" class="wp-caption aligncenter" style="width: 510px"><img class="size-full wp-image-1205" title="OLYMPUS DIGITAL CAMERA" src="http://www.kabayview.com/wp-content/uploads/2012/04/dropcap2_illuminated_detail.jpg" alt="" width="500" height="330" /><p class="wp-caption-text">Figure 2: Detail of Latin Bible, 1407. Lettering by Gerard Brils, Belgium. Note the subtle use of color to emphasize the start of a new sentence. (Image: Adrian Pingstone)</p></div>
<p>&nbsp;</p>
<h3>Initial Caps In Printed Books</h3>
<p>Of course, not all initial caps were as sexy as the image of St. Peter illuminated with pure gold. Initial caps were also used for mundane purposes: like indicating the alphabetical order of ideas. Routine today, alphabetizing was not originally used to organize information in books. Figure 3 shows a page from the table of contents of an <em>incunabula</em> (an early printed book). The initial caps were written in after the book was printed. The quality of lettering is not as beautiful as the St. Peter example above, but the letters serve an important purpose for the reader.</p>
<div id="attachment_1206" class="wp-caption aligncenter" style="width: 510px"><img class="size-full wp-image-1206" title="dropcap3_alphabetized" src="http://www.kabayview.com/wp-content/uploads/2012/04/dropcap3_alphabetized.jpg" alt="" width="500" height="330" /><p class="wp-caption-text">Figure 3: The last page of a table of contents from an early printed book. 1476. Initial caps added after the book was printed. (Image: used by permission of University of Glasgow, Special Collections)</p></div>
<p>&nbsp;</p>
<p>Early printed books were often designed to replicate manuscripts. Printers left space in and around the text—so owners could hire an artisan to illustrate initial caps and borders. Figure 4 is an example of one such book; no initial cap was ever added. Note the initial space and guide letter provided for the illustrator. Even without the final initial cap, the text is readable (if you read Latin).</p>
<p>Figure 5 is a printed Bible from the same time and place (Venice, 1480). After it was printed, artisans supplied <em>rubricated</em> (written in red), decorated, and illuminated initials—thus continuing the formal tradition of the manuscript book.</p>
<p>Not all printed books required an artisan to finish the initial caps. Printers designed and created modular initial caps almost from the beginning. Figure 6 shows two <em>inhabited</em> caps (the illustrations do not represent a specific person or scene) set side-by-side, each starting a different translation of the New Testament. The inhabited caps and border where printed along with the text.</p>
<div id="attachment_1207" class="wp-caption aligncenter" style="width: 510px"><img class="size-full wp-image-1207" title="dropcap4_space" src="http://www.kabayview.com/wp-content/uploads/2012/04/dropcap4_space.jpg" alt="" width="500" height="330" /><p class="wp-caption-text">Figure 4: The printer left an initial space with guide letter. After printing, an artisan could be hired to add an initial cap. Venice, 1479. (Image: used by permission of University of Glasgow, Special Collections)</p></div>
<p>&nbsp;</p>
<div id="attachment_1208" class="wp-caption aligncenter" style="width: 510px"><img class="size-full wp-image-1208" title="dropcap5_added" src="http://www.kabayview.com/wp-content/uploads/2012/04/dropcap5_added.jpg" alt="" width="500" height="330" /><p class="wp-caption-text">Figure 5: Printed Latin Bible. An artisan added various initials after the book was printed. Venice, 1480. (Image: used by permission of University of Glasgow, Special Collections)</p></div>
<p>&nbsp;</p>
<div id="attachment_1209" class="wp-caption aligncenter" style="width: 510px"><img class="size-full wp-image-1209" title="dropcap6_printed" src="http://www.kabayview.com/wp-content/uploads/2012/04/dropcap6_printed.jpg" alt="" width="500" height="330" /><p class="wp-caption-text">Figure 6: The first complete published text of the Greek New Testament. The inhabited caps and border were printed with the text. Basel, 1516. (Image: used by permission of University of Glasgow, Special Collections)</p></div>
<p>&nbsp;</p>
<p>The role of written texts changed starting in the mid-1600’s, and initial caps fell out of favor. Newspapers allowed readers to share current ideas and information, scientific inquiry provided a basis of rational thought, and the typographic page simplified. The relationship between type and image continued to shift—primarily influenced by industrialization (which in turn influenced the art of printing, the speed at which goods could be produced and transported, and the development of a literate middle-class).</p>
<h3>Drop Caps On The Web</h3>
<p>Today, initial caps are no longer necessary; they are used primarily as decorative elements. Used for centuries in religious and scholarly texts, initial caps are associated with and communicate an “old” or “traditional” feeling. Thus, when we want to design a Web page that feels traditional, elegant, or historic, we find ourselves wanting to use drop caps.</p>
<p>There are four common methods for creating drop caps in HTML and CSS. But which one is best?</p>
<p>In an attempt to answer that question, I tested all four methods across 82 different browser-version-operating system combinations—including smart phones. (If you’re interested, you can read a <a href="http://media.smashingmagazine.com/wp-content/uploads/2012/02/testing_browsers.pdf">list of the combinations</a> and why I chose them).  In an attempt to identify which methods are accessible, I also tested them using VoiceOver on the mac, with Safari 5.1.1.</p>
<p>Which method is best? The answer is… not clear-cut.</p>
<h4>Method 1: Image Replacement</h4>
<p>If you want a drop cap that shows up consistently across all operating systems—including smart phones—there isn’t one. But using the <em>Image Replacement</em> method (Figure 7) comes close. Using an image for the drop cap holds up beautifully across 79 of the 82 combinations tested. It shifted placement on Opera Mini 5.1 (Android 2.2), and Mobile Safari 4.0.5 (iPhone 4, iPhone 3GS).</p>
<div id="attachment_1210" class="wp-caption aligncenter" style="width: 510px"><img class=" wp-image-1210   " title="dropcap7_image_replacement" src="http://www.kabayview.com/wp-content/uploads/2012/04/dropcap7_image_replacement.jpg" alt="" width="500" height="330" /><p class="wp-caption-text">Figure 7: An inhabited initial cap similar to those used in the 1516 Greek New Testament shown in Figure 6 above. (1) Using an image for the drop cap holds up beautifully across 79 of the 82 browser-version-operating system combinations tested. (2) It shifted down slightly on Opera Mini 5.1 (Android 2.2). (3) It shifted up on Mobile Safari 4.0.5 (iPhone 4, iPhone 3GS), resulting in an awkward space below the image. (Drop cap illustration: Bruce Maddocks)</p></div>
<p style="text-align: center;"><em><br />
</em></p>
<p> <strong>HTML for the “Image Replacement” Example</strong></p>
<p><code>&lt;</code><code>p</code><code>&gt;&lt;</code><code>span</code> <code>class</code><code>=</code><code>"drop f"</code><code>&gt;F&lt;/</code><code>span</code><code>&gt;ine typography does not … &lt;/</code><code>p</code><code>&gt;</code></p>
<p>Note that I used two classes for the span. This allowed me to use one class (drop) to style the space, and use another class (f) to specify the image of the letter.</p>
<p><strong>CSS for the “Image Replacement” Example</strong></p>
<p>.drop{<br />
display:block;<br />
float:left;<br />
width:72px;<br />
height:72px;<br />
margin-top:5px;<br />
padding-right:8px;<br />
text-indent: -9000px;<br />
}<br />
.f{<br />
background: url(images/f_small.jpg) 0 0 no-repeat;<br />
}</p>
<p>Note that I set the width and height of the space to the same dimensions as the image used to represent the drop cap. The text-indent attribute is used to place the actual letter outside the visible area of the space. We don’t want to see the HTML letter, but it’s important to include it so browsers without CSS enabled will show the entire word.</p>
<p>View the <a href="http://media.smashingmagazine.com/wp-content/uploads/2012/02/image_replace1.html">original <em>Image Replacement</em> example</a> HTML document.</p>
<h4>Method 2: Letter Over a Background Image</h4>
<p>Placing a letter over a background image is a bit less successful (Figure 8). It works consistently across 77 of the 82 combinations tested. It posed a problem on the same three browsers as the <em>Image Replacement</em> method above—Opera Mini 5.1 (Android 2.2), and Mobile Safari 4.0.5 (iPhone 4, iPhone 3GS)—as well as Windows Vista IE7 and Windows XP IE7. Granted, PC users increasingly use Windows 7 with IE8 or higher, so the last two browsers may not be a problem.</p>
<div id="attachment_1211" class="wp-caption aligncenter" style="width: 510px"><img class="size-full wp-image-1211  " title="dropcap8_bground_image" src="http://www.kabayview.com/wp-content/uploads/2012/04/dropcap8_bground_image.jpg" alt="" width="500" height="383" /><p class="wp-caption-text">Figure 8: A decorated initial cap similar to one used in the 1480 Printed Latin Bible shown in Figure 5 above—created using a background image. (1) Placing a letter over a background image holds up beautifully across 77 of the 82 browser-version-operating system combinations tested. (2) The drop cap lost styling on the Opera Mini 5.1 (Android 2.2). (3) The letter and image shifted up on Mobile Safari 4.0.5 (iPhone 4, iPhone 3GS), resulting in an awkward space below the image. (4) The letter was cut off on Windows Vista IE7 and Windows XP IE7.</p></div>
<p>&nbsp;</p>
<p><strong>HTML for the “Letter Over Background Image” Example</strong></p>
<p><code>&lt;</code><code>p</code><code>&gt;&lt;</code><code>span</code> <code>class</code><code>=</code><code>"cap"</code><code>&gt;A&lt;/</code><code>span</code><code>&gt;nother way to … &lt;/</code><code>p</code><code>&gt;</code></p>
<p><strong>CSS for the “Letter Over Background Image” Example</strong></p>
<p>.cap{<br />
display:block;<br />
float:left;<br />
width:72px;<br />
height:52px;<br />
font-size: 500%;<br />
color:#ffffff;<br />
margin-top:5px;<br />
padding-top:20px;<br />
margin-right:8px;<br />
text-align:center;<br />
background: url(images/flower.jpg) 0 0 no-repeat;<br />
}</p>
<p>Note that I added a padding-top in this version so the letter doesn’t touch the top edge of the background image.</p>
<p>View the <a href="http://media.smashingmagazine.com/wp-content/uploads/2012/02/image_background.html">original <em>Letter Over Background Image</em> example</a> HTML document.</p>
<h4>Method 3: Span Class, No Image</h4>
<p>Creating a class for the drop cap (without a background image) is even slightly less successful (Figure 9). It works consistently across 76 of the 82 combinations tested. It posed a problem on the same five browsers as the <em>Letter with a Background Image</em> method above—Opera Mini 5.1 (Android 2.2), Mobile Safari 4.0.5 (iPhone 4, iPhone 3GS), Windows Vista IE7 and Windows XP IE7—as well as Windows XP IE6. Again, PC users increasingly use Windows 7 with IE8 or higher, so the IE6 browser may not be a problem.</p>
<div id="attachment_1213" class="wp-caption aligncenter" style="width: 510px"><img class="size-full wp-image-1213  " title="dropcap9_spanclass" src="http://www.kabayview.com/wp-content/uploads/2012/04/dropcap9_spanclass.jpg" alt="" width="500" height="330" /><p class="wp-caption-text">Figure 9: A simple initial cap similar to those used in the 1480 Printed Latin Bible shown in Figure 5 above. (1) Creating a class for the drop cap without a background image holds up across 76 of the 82 browser-version-operating system combinations tested. (2) The drop cap lost styling on the Opera Mini 5.1 (Android 2.2). (3) It shifted up on Mobile Safari 4.0.5 (iPhone 4, iPhone 3GS), resulting in an awkward space below the image. (4) The letter was cut off on Windows Vista IE7, Windows XP IE7, and Windows XP IE6.</p></div>
<p>&nbsp;</p>
<p><strong>HTML for the “Span Class, No Image” Example</strong></p>
<p><code>&lt;</code><code>p</code><code>&gt;&lt;</code><code>span</code> <code>class</code><code>=</code><code>"dropcap"</code><code>&gt;H&lt;/</code><code>span</code><code>&gt;istorically,… &lt;/</code><code>p</code><code>&gt;</code></p>
<p><strong>CSS for the “Span Class, No Image” Example</strong></p>
<p>.dropcap{<br />
float:left;<br />
font-size:400%;<br />
margin-top:14px;<br />
margin-right:5px;<br />
color:#8C8273;<br />
}</p>
<p>Note that I added a margin-right of 5px in this version. The letter H worked well with this amount of space. The margin-right may need to change depending on the shape of the letter being used as a drop cap.</p>
<p>View the <a href="http://media.smashingmagazine.com/wp-content/uploads/2012/02/class_no_image.html">original <em>Span Class, No Image</em> example</a> HTML document.</p>
<h4>Method 4: First-Child:First-Letter</h4>
<p>When it comes to consistency, using a p:first-child:first-letter is the least successful (Figure 10). It posed problems with the same 6 combinations as the <em>Span Class, No Image</em> method above—Opera Mini 5.1 (Android 2.2), Mobile Safari 4.0.5 (iPhone 4, iPhone 3GS), Windows Vista IE7, Windows XP IE7 and Windows XP IE6—and had inconsistent placement in the remaining 76 combinations tested. When setting the original drop cap placement for Firefox, 31 combinations remained properly aligned. The drop caps in the remaining 44 combinations were too high.</p>
<div id="attachment_1214" class="wp-caption aligncenter" style="width: 510px"><img class="size-full wp-image-1214  " title="dropcap10_firstletter" src="http://www.kabayview.com/wp-content/uploads/2012/04/dropcap10_firstletter.jpg" alt="" width="500" height="432" /><p class="wp-caption-text">Figure 10: A rubricated (red) initial cap similar to those used in the 1476 and 1480 early printed books shown in Figures 3 and 5 above. (1) Using first:child-first:letter to create the drop cap resulted in proper placement in 31 of the 82 browser-version-operating system combinations tested. Note: the original placement was determined viewing the page in Firefox. (2) The drop caps in 45 versions were too high, resulting in an odd relationship between the drop cap and the text. (3) The drop cap lost styling on the Opera Mini 5.1 (Android 2.2). (4) It shifted up on Mobile Safari 4.0.5 (iPhone 4, iPhone 3GS), resulting in an awkward space below the image. (5) Again, the letter shifted up (Windows Vista IE7, Windows XP IE7), allowing one of the lines of text to move over and creating an awkward relationship with the text. (6) The letter lost all styling (including space) in Windows XP IE6.</p></div>
<p>&nbsp;</p>
<p><strong>HTML for the “First-Child:First-Letter (Firefox)” Example</strong></p>
<p><code>&lt;</code><code>p</code><code>&gt;Historically, initial letters… &lt;/</code><code>p</code><code>&gt;</code></p>
<p><strong>CSS for the “First-Child:First-Letter (Firefox)” Example</strong></p>
<p>p:first-child:first-letter{<br />
float:left;<br />
font-size:400%;<br />
margin-top:7px;<br />
margin-right:5px;<br />
color:#992E00;<br />
}</p>
<p>View the <a href="http://media.smashingmagazine.com/wp-content/uploads/2012/02/first_letter_firefox.html">original <em>First Letter, FireFox</em> example</a> HTML document.</p>
<h4>Testing for Accessibility: VoiceOver</h4>
<p>Before deciding which of the four methods is best, I wanted to test them all for accessibility. Getting type to look good sometimes means choosing presentational markup over semantic markup—which can affect how well a screen reader reads a Web page.</p>
<p>Using VoiceOver on the mac (Safari 5.1.1), only the <em>First-Child:First-Letter</em> method was read correctly. The other three methods use a class to separate the drop cap from the rest of the text; VoiceOver verbally separates the initial letter from the rest of the word (e.g. “H”… “istorically”).</p>
<p>Thus, the method that is least successful visually is most successful in terms of accessibility. So I decided to do some more testing before choosing a best method.</p>
<h4>Method 4 Revisited: First-Child:First-Letter—Placement Based on Both Firefox and Windows 7 IE8</h4>
<p>Using a p:first-child:first-letter is still the least consistent method. It posed problems with the same 6 combinations as the <em>First-Child:First-Letter</em> method above—and continued to have inconsistent placement in the remaining 76 combinations tested.</p>
<p>But when I increased the size of the drop cap and set the original placement based on simultaneously considering the results in both Firefox and Windows 7 IE8, the shift in placement didn’t feel as random (Figure 11). Some drop caps align with the baseline of the second line of text (Figure 11:1). Some align with the top of the first line of text (Figure 11:2). There is too much space below the drop caps that align to the top—creating a white square that pops out and calls attention to itself—but if one is a stickler for accessibility and semantic markup, this method could work.</p>
<div id="attachment_1220" class="wp-caption aligncenter" style="width: 510px"><img class="size-full wp-image-1220" title="dropcap11_first_letter_revisited" src="http://www.kabayview.com/wp-content/uploads/2012/04/dropcap11_first_letter_revisited.jpg" alt="" width="500" height="212" /><p class="wp-caption-text">Figure 11: When working with first-child:first-letter, simultaneously consider multiple browsers when placing the drop cap. (1) The revisited drop cap, viewed in Windows 7 IE8. The letter aligns nicely with the baseline of the second line of text. My original first-child:first-letter drop cap (in red) didn’t line up with anything when viewed in Windows 7 IE8. The placement looked random. (2) The same revisited drop cap when viewed in Firefox. The drop cap continues to come in lower, but due to carefully chosen font-size and margin-top, it continues to align with the top of the first line of text. My original first-child:first-letter dop cap (in red) was perhaps more successful. It didn’t have the white space below it when viewed in Firefox. The first-child:first-letter method is not perfect, but might be a good choice when aiming for accessibility.</p></div>
<p>&nbsp;</p>
<p><strong>HTML for the “First-Child:First-Letter (revisited)” Example</strong></p>
<p><code>&lt;</code><code>p</code><code>&gt;Historically, initial letters… &lt;/</code><code>p</code><code>&gt;</code></p>
<p><strong>CSS for the “First-Child:First-Letter (revisited)” Example</strong></p>
<p>p:first-child:first-letter{<br />
float:left;<br />
margin-top:7px;<br />
font-size:70px;<br />
margin-right:5px;<br />
color:#3D3529;<br />
}</p>
<p>View the <a href="http://media.smashingmagazine.com/wp-content/uploads/2012/02/first_letter_ie.html" target="_blank">original <em>First Letter, Revisited</em> example</a> HTML document.</p>
<h3>Letter Shapes And Letterspacing</h3>
<p>Letters have different shapes (round, triangular, open, and square) which means they have different amounts of visual space around them (Figures 12 and 13).</p>
<div id="attachment_1221" class="wp-caption aligncenter" style="width: 510px"><img class="size-full wp-image-1221" title="dropcap12_letterspacing" src="http://www.kabayview.com/wp-content/uploads/2012/04/dropcap12_letterspacing.jpg" alt="" width="500" height="200" /><p class="wp-caption-text">Figure 12: The letters A and T naturally have more visual space than the letters O and M. Font designers adjust letterspacing so letters appear more even in text; the A and T are “tightened” in the final font.</p></div>
<p>&nbsp;</p>
<div id="attachment_1222" class="wp-caption aligncenter" style="width: 510px"><img class="size-full wp-image-1222" title="dropcap13_letterspacing_diff_font" src="http://www.kabayview.com/wp-content/uploads/2012/04/dropcap13_letterspacing_diff_font.jpg" alt="" width="500" height="200" /><p class="wp-caption-text">Figure 13: Letter shapes and letterspacing change from font to font. Various Os have different visual space.</p></div>
<p>&nbsp;</p>
<p>A well-designed font takes into account the varying amounts of visual space. Triangular and open letters are designed with tighter letterspacing (space is taken out). Square letters are designed with looser letterspacing (space is added). This approach to spacing is great in text; if type designers didn’t adjust spacing in a font, we’d end up with big gaps of space in the middle of words! But unfortunately, adjusted letterspacing creates problems in drop caps.</p>
<h4>Letterspacing and the “Span Class, No Image” Method</h4>
<p>Figure 14 shows various letters set as drop caps using the <em>Span Class, No Image </em>method. In Figure 14:1, the letters O and T look great, but the other four letters (C, A, K, L) are all a bit too tight to the text. In fact, the A and L look like they belong with the second line of their texts! (“A use various…” “Lit’s an open…”) Due to their open or triangular shapes, C, A, K and L have slightly tightened letterspacing in the font. This makes them look tight when used as drop caps, even though all the letters are set with the same right-margin: 5px.</p>
<p>In Figure 14:2, the letters are more comfortably spaced with their texts. Each letter has a unique class styled with an appropriate margin to each. Right margins range from 5px to 8px.</p>
<div id="attachment_1223" class="wp-caption aligncenter" style="width: 510px"><img class="size-full wp-image-1223" title="dropcap14_letterspacing_classes" src="http://www.kabayview.com/wp-content/uploads/2012/04/dropcap14_letterspacing_classes.jpg" alt="" width="500" height="403" /><p class="wp-caption-text">Figure 14: Different letters need a different amount of right margin. (1) The O and T have appropriate space around them. The other letters are too tight to their texts. (2) Using a unique class for each letter, right margins have been adjusted. The change is subtle, but the L no longer looks like it belongs with the second line of text!</p></div>
<p>&nbsp;</p>
<p><strong>HTML for the “Span Class Letterspacing” Example</strong></p>
<p>&lt;p&gt;&lt;span&gt;O&lt;/span&gt;nce upon a time,&#8230; &lt;/p&gt;<br />
&lt;p&gt;&lt;span&gt;A&lt;/span&gt;nd when she tested&#8230; &lt;/p&gt;<br />
&lt;p&gt;&lt;span&gt;T&lt;/span&gt;he drop caps used&#8230; &lt;p&gt;<br />
&lt;p&gt;&lt;span&gt;C&lt;/span&gt;an you use&#8230; &lt;/p&gt;<br />
&lt;p&gt;&lt;span&gt;K&lt;/span&gt;ittens don&amp;rsquo;t&#8230; &lt;/p&gt;<br />
&lt;p&gt;&lt;span&gt;L&lt;/span&gt;ater she realized&#8230; &lt;/p&gt;</p>
<p><strong>CSS for the “Span Class Letterspacing” Example</strong></p>
<p>.dropcap_a, .dropcap_c, .dropcap_k, .dropcap_l,.dropcap_o, .dropcap_t {<br />
float:left;<br />
font-size:370%;<br />
margin-top:14px;<br />
color:#8C8273;<br />
}<br />
.dropcap_o,.dropcap_t{<br />
margin-right:5px;<br />
}<br />
.dropcap_k {<br />
margin-right:6px;<br />
}<br />
.dropcap_a, .dropcap_c {<br />
margin-right:7px;<br />
}<br />
.dropcap_l{<br />
margin-right:8px;<br />
}</p>
<p>View the <a href="http://media.smashingmagazine.com/wp-content/uploads/2012/02/class_no_image_letterspace.html" target="_blank">original <em>Span Class Letterspacing</em> example</a> HTML document.</p>
<p><strong>Letterspacing and the “First-Child:First-Letter” Method</strong><br />
Letter shapes and letterspacing create similar problems in drop caps set using the <em>First-Child:First-Letter</em> method. In Figure 15, there is a generous space between the O and its text. The A, on the other hand, is too tight and looks like it belongs with the second line (“A various letters…”). Look at the O again; the curved bottom of the letter adds visual space and makes it look like it’s floating higher than the A and T in relation to the text.</p>
<p>The T has the best spacing—it’s tighter than the O and looser than the A—but creates an odd enclosed white space between the stem (the vertical stroke) of the T and the text. This happens when using the <em>First-Child:First-Letter</em> method because we have less control over the vertical placement of the drop cap (remember, we have to compromise size and placement to achieve the best results across browsers).</p>
<div id="attachment_1225" class="wp-caption aligncenter" style="width: 510px"><img class="size-full wp-image-1225" title="dropcap15_OAT_compare_letterspacing" src="http://www.kabayview.com/wp-content/uploads/2012/04/dropcap15_OAT_compare_letterspacing.jpg" alt="" width="500" height="369" /><p class="wp-caption-text">Figure 15: Two methods that apply identical spacing to every drop cap. (1) Using first-child:first-letter creates inconsistent visual space if different letters are used as drop caps on a web site. (2) Using an image behind the drop cap creates a consistent visual space for the drop caps to inhabit.</p></div>
<p>&nbsp;</p>
<p>Unfortunately, we can’t adjust the letterspacing; it’s not possible to create 26 unique versions of first-child:first-letter and style them using only HTML and CSS. (If anyone has figured out a solution, please share it with us in the comments.) Thus a website using the <em>First-Child:First-Letter</em> method will be riddled with awkwardly spaced drop caps.</p>
<p><strong>Letterspacing and the “Image Replacement” and “Letter Over an Image” Methods</strong></p>
<p>Both the <em>Image Replacement</em> method and the <em>Letter Over an Image</em> method (Figure 15:2) have appropriate spacing regardless of the letter used. These methods set a consistent width to hold the image; variations in letterspacing take place within the image border—not between the drop cap and the text.</p>
<p>But what if you want to use the <em>image replacement</em> method to insert images of drop caps that don’t have a consistent width?</p>
<p>Figure 16 shows various letters set as drop caps using the <em>Image Replacement </em>method; without a background, the drop caps no longer have a consistent width. In the left panel (Figure 16:1), the letter M looks great, but the letters O and I have awkward spaces between the drop cap and the text. This variation in spacing is not due to letterspacing in the font; it occurs because the letters themselves have different widths. In the right panel (Figure 16:2), the letters are more comfortably spaced with their texts. Each letter has a unique class styled with an appropriate width. Widths range from 41px to 85px.</p>
<div id="attachment_1226" class="wp-caption aligncenter" style="width: 510px"><img class="size-full wp-image-1226" title="dropcap16_OIM_compare_letterswidth" src="http://www.kabayview.com/wp-content/uploads/2012/04/dropcap16_OIM_compare_letterswidth.jpg" alt="" width="500" height="445" /><p class="wp-caption-text">Figure 16: Letter width can also affect the amount of visual space around a letter. (1) The M has appropriate space around it. The O and I are narrower, so the space provided is too wide. (2) Using a unique class for each letter, widths have been adjusted.</p></div>
<p>&nbsp;</p>
<p><strong>HTML for the “Image Replacement, No Background” Example</strong></p>
<p>&lt;p&gt;&lt;span&gt;O&lt;/span&gt;nce upon a time&#8230; &lt;/p&gt;<br />
&lt;p&gt;&lt;span&gt;I&lt;/span&gt;nitially, she made sure&#8230; &lt;/p&gt;<br />
&lt;p&gt;&lt;span&gt;M&lt;/span&gt;any shapes were&#8230; &lt;/p&gt;</p>
<p>Note that I used two classes for each span. This allowed me to use one class (drop_o) to style the space, and use another class (o) to specify the image of the letter.</p>
<p><strong>CSS for the “Image Replacement, No Background” Example</strong></p>
<p>.drop_o, .drop_i, .drop_m{<br />
display:block;<br />
float:left;<br />
height:72px;<br />
margin-top:8px;<br />
text-indent: -9000px;<br />
}<br />
.drop_o {<br />
width:73px;<br />
}<br />
.drop_i {<br />
width:41px;<br />
}<br />
.drop_m {<br />
width:85px;<br />
}<br />
.o{<br />
background: url(images/didot_o.jpg) 0 0 no-repeat;<br />
}<br />
.i{<br />
background: url(images/didot_i.jpg) 0 0 no-repeat;<br />
}<br />
.m{<br />
background: url(images/didot_m.jpg) 0 0 no-repeat;<br />
}</p>
<p>Note that I set the height of the space to the same dimensions as the image used to represent the drop cap. The widths are wider than the images; width provides a margin of space between the drop cap and the text.</p>
<p>View the <a href="http://media.smashingmagazine.com/wp-content/uploads/2012/02/image_replace_no_background.html">original <em>Image Replacement, No Background</em> example</a> HTML document.</p>
<h3>The Best Method: Merging Tradition And Technology</h3>
<p>Balancing issues of consistency, accessibility, and letterspacing, I recommend using either <em>Method 1: Image Replacement</em> or <em>Method 2: Letter Over an Image</em>. Both hold up well across most browsers tested; both methods allow Web designers to create elegant, decorative drop caps.</p>
<p>If you absolutely do not want to use images for your drop caps, then I recommend using <em>Method 3: Span Class, No Image</em>.</p>
<h4>Drop Caps Do Not Promote Readability</h4>
<p>Some may disagree with my recommendation and say that <em>First-Child:First-Letter</em> is a better choice due to accessibility issues; it was the only method to work properly with VoiceOver.</p>
<p>I understand that argument – I usually aim for accessibility. But when it comes to drop caps, I find the screen reader’s “incorrect” verbalization is ironically closer to the experience a sighted reader has. When reading text with a drop cap, we always “read” the letter, then the partial word, and then have to piece the two together. (Try it with Figure 16 above. Do you read “O” and then “nce” and then do a bit of mental gymnastics to read the word “Once?”)</p>
<p>The visual separation caused by using a drop cap interferes with word recognition for everyone. Drop caps are decorative elements. When we use them, we are setting a tone—often at the expense of readability.</p>
<h4>Beautiful Drop Caps Can Be Inserted into the HTML Automatically</h4>
<p>One could argue that <em>First-Child:First-Letter</em> is still a better choice because it eliminates the need to insert syntax in the HTML for every drop cap. Using first-child:first-letter, drop caps are created automatically.</p>
<p>But there’s another way to automatically create drop caps. With a little javascript you can insert span classes (with or without images) into your HTML. You can even create multiple unique classes (e.g. 52 classes, two for each letter) and articulate which class—or classes—to apply.</p>
<p>Jason Lynes of NorthTemple.com provides a clearly written <a href="http://northtemple.com/2008/12/02/hot-and-graceful-jquery-dropcaps" target="_blank">case study on using jQuery and CSS to insert <em>Image Replacement</em> drop caps</a>. Lynes’ case study highlights an article for the LDS Church. I’m not inviting conversation about the content of the article; I am providing the case study as an excellent tutorial on “automating” drop caps with jQuery and CSS.</p>
<p>I’ve tested Lynes’ method – I used it to create a page of <em>Span Class, No Image</em> drop caps. It works like a charm and degrades beautifully (drop caps revert to plain text on browsers that are not javascript enabled). View my <a href="http://media.smashingmagazine.com/wp-content/uploads/2012/02/span_class_jquery.html">original <em>Span Class, jQuery</em> example</a> HTML document.</p>
<h4>Beautiful Drop Caps Take Time and Effort</h4>
<div id="attachment_1228" class="wp-caption aligncenter" style="width: 510px"><img class="size-full wp-image-1228" title="dropcap17_compare_quality" src="http://www.kabayview.com/wp-content/uploads/2012/04/dropcap17_compare_quality.jpg" alt="" width="500" height="330" /><p class="wp-caption-text">Figure 17: Another look at initial caps from (clockwise from top left) 1407, 1476, 1480, and 1479. (1) Two of the initial caps are painted with care. (2) The other two are examples of “quick solutions” to initial caps: a set of hastily written caps and an initial space set aside for an artisan to fill in.</p></div>
<p>&nbsp;</p>
<p>Deciding to use drop caps on a website means making a conscious choice to use a primarily decorative element. Unlike initial caps in manuscripts and incunabula, a drop cap on the Web doesn’t add value in terms of usability or readability; its main purpose is to look good. And making a drop cap look good—whether in a manuscript, an incunabula, or on the Web—takes time (Figure 17).</p>
<p>Even if we automate our drop caps with jQuery, we need to do the preliminary work—make images, test letterspacing, and set up 26 (or 52) unique classes. Creating beautiful, high quality drop caps may sound like a chore, but we are continuing a respected tradition that is almost two thousand years old. When we look back through history, we see the best initial caps have always taken time and effort.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.kabayview.com/typography/drop-caps-historical-use-and-current-best-practices-with-css/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Responsive CSS Grid &#8211; oldest trick in the book</title>
		<link>http://www.kabayview.com/responsive-web-design/responsive-css-grid-oldest-trick-in-the-book</link>
		<comments>http://www.kabayview.com/responsive-web-design/responsive-css-grid-oldest-trick-in-the-book#comments</comments>
		<pubDate>Fri, 13 Apr 2012 14:16:29 +0000</pubDate>
		<dc:creator>Lynda Damiata</dc:creator>
				<category><![CDATA[Responsive Web Design]]></category>

		<guid isPermaLink="false">http://www.kabayview.com/?p=1197</guid>
		<description><![CDATA[April 04, 2012 onderhond.com :: responsive Even though I believe in responsive design, I&#8217;m not totally happy with the current resources both developers and web users have to their disposal. Then again, doing nothing at all isn&#8217;t helping anyone either, so I went ahead and made a responsive design anyway. If you want to see <a href='http://www.kabayview.com/responsive-web-design/responsive-css-grid-oldest-trick-in-the-book'> [read more]</a>]]></description>
			<content:encoded><![CDATA[<p>April 04, 2012<br />
<a href="http://www.onderhond.com/">onderhond.com</a> ::</p>
<h1>responsive</h1>
<p>Even though I believe in responsive design, I&#8217;m not totally happy with the current resources both developers and web users have to their disposal. Then again, doing nothing at all isn&#8217;t helping anyone either, so I went ahead and made a responsive design anyway. If you want to see the resulting css file, you can check the <a href="http://www.onderhond.com/style/onderhond-responsive.less" target="_blank">responsive onderhond.com css here</a>.</p>
<p><img class="aligncenter size-full wp-image-1199" title="responsive-grid" src="http://www.kabayview.com/wp-content/uploads/2012/04/responsive-grid.jpg" alt="" width="572" height="180" /></p>
<p>I&#8217;m almost ashamed to admit this, but it was the first time I actually coded a responsive design. Sure I&#8217;ve been reading about responsive the last few years, keeping myself as up to date as possible, but my focus on html and my shaky beliefs in the hands-on implementation kept me clear from actually sitting down and implementing such a design. For my site I also went the wrong way around. Responsive goes hand in hand with mobile-first, in my case the desktop design was already there and had to be adapted to a mobile context.</p>
<p>However, I found myself somewhat surprised at the ease of adapting a desktop design to mobile. When I started, I had only three specific requirements for my mobile design:</p>
<ul>
<li>I wasn&#8217;t going to support anything with a resolution lower than 320px.</li>
<li>I was going for a liquid layout while focusing on content breakpoints rather than device breakpoints</li>
<li>The content column was the only liquid column.</li>
</ul>
<p>The third point in particular is an important one, as this method only requires one liquid column. Many responsive grids I saw before featured all-liquid columns. In my experience, the context (aside) and navigation (nav) columns are pretty designed by width already, so making them liquid would only lead to an unmanageable mess. Instead, I was going to focus on the content column and have the design break to a single column layout when the content area became too small to use.</p>
<h1>the grid</h1>
<p>The funny thing was that the grid system I&#8217;ve been using for the past 5 years already provided this exact behavior. For years I&#8217;ve been coding liquid layouts, though in practice a fixed with on the parent container always made sure the actual design was fixed. Changing this width to a max-width was enough to trigger the liquid content column behavior I was aiming for.</p>
<p><code> /* html */ &lt;div&gt; &lt;section&gt; content goes here &lt;/section&gt;<br />
&lt;aside&gt; fixed context column&lt;/aside&gt;<br />
&lt;/div&gt;<br />
/* css */<br />
.grid{padding-right:15em;}<br />
.grid &gt; section {float:left; width:100%;}<br />
.grid &gt; aside {float:right; width:15em; margin-right:-15em;}</code></p>
<p>The code above is an age-old piece of html/css that allows for easy equal height, source-order independent grids. You can switch the section and aside element in the html source without any changes needed to the css. More important though is that the section (the content column) takes up all the available space. Change the width on the parent and the size of the content column will change accordingly. Even better, this thing can be made to work all down to ie6.</p>
<p>People may remember an article I wrote a good 2.5 years ago (<a href="http://www.onderhond.com/blog/work/away-with-widths-use-and-abuse">away with widths</a>) where I went against the abuse (or call it over-use) of explicit widths in web design. It turns out that with responsive design raging this little best practice made my life a whole lot easier. After changing the width of my page to a max-width with the same value, all I had to was resize my browser window to find out where my original design broke and add my breakpoints there. Currently the grid breaks down at 630px, leaving me with the following piece of css:</p>
<p><code> .grid &gt; section, .grid &gt; aside {margin:1em 0;}<br />
@media all and (min-width:630px) {<br />
.grid {padding-right:15em; overflow:hidden;}<br />
.grid &gt; section {float:left; width:100%; margin:0;}<br />
.grid &gt; aside {float:right; width:15em; margin:0; margin-right:-15em;}<br />
} </code></p>
<p>And that&#8217;s all there is to it really. Everything below 630 gets a single-column experience (though I&#8217;m not quite sure what to do with the context column, leaving it in its original size looks weird, but stretching it across the entire available width is probably even sloppier &#8211; guess that&#8217;s why people are preaching the mobile-first approach). All in all it took me about 7-8 hours to adapt everything and to get the responsive layout live. Not bad for someone who never coded a responsive layout before, I&#8217;d expected a lot worse to be honest.</p>
<p>If you want a peak at the grid in action, check out the little <a href="http://onderhond.com/testpages/responsive-grid.html">responsive grid test page</a> I made. It may not be new and/or cutting-edge, but somehow I haven&#8217;t seen it used much in relation to responsive (yet).</p>
<section>
<h1>conclusion</h1>
<p>Best practices, even when they don&#8217;t have an immediate effect, are important, if not essential for future-proof coding. The grid system I&#8217;ve been using for about 5 years now suddenly proves very effective in accommodating responsive layouts. These are the finer moments in one&#8217;s career. Things are a little different if you want all-liquid columns of course, but I&#8217;m not quite sure I think that&#8217;s a very good idea in the first place.</p>
<p>I&#8217;m still trying to find a good way to switch back to the old (fixed) layout for web users who don&#8217;t like the responsive version (which I know exist), you can expect this functionality in the near future.</p>
</section>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.kabayview.com/responsive-web-design/responsive-css-grid-oldest-trick-in-the-book/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Six CSS Layout Features To Look Forward To</title>
		<link>http://www.kabayview.com/css3/six-css-layout-features-to-look-forward-to</link>
		<comments>http://www.kabayview.com/css3/six-css-layout-features-to-look-forward-to#comments</comments>
		<pubDate>Mon, 09 Jan 2012 19:48:51 +0000</pubDate>
		<dc:creator>Lynda Damiata</dc:creator>
				<category><![CDATA[CSS3]]></category>

		<guid isPermaLink="false">http://www.kabayview.com/?p=1171</guid>
		<description><![CDATA[By Divya Manian &#124; December 15th, 2011 &#124; smashingmagazine.com :: A few concerns keep bobbing up now and then for Web developers, one of which relates to how to lay out a given design. Developers have made numerous attempts to do so with existing solutions. Several articles have been written on finding the holy grail <a href='http://www.kabayview.com/css3/six-css-layout-features-to-look-forward-to'> [read more]</a>]]></description>
			<content:encoded><![CDATA[<p>By <a title="Posts by Divya Manian" href="http://coding.smashingmagazine.com/author/divya-manian/" rel="author">Divya Manian</a> | December 15th, 2011 |<br />
<a href="http://smashingmagazine.com/" target="_blank">smashingmagazine.com</a> ::</p>
<p>A few concerns keep bobbing up now and then for Web developers, one of which relates to how to lay out a given design. Developers have made numerous attempts to do so with existing solutions. Several articles have been written on finding the <a href="http://www.alistapart.com/articles/holygrail/">holy grail of CSS layouts</a>, but to date, not a single solution works without major caveats. At the <a href="http://w3conf.org/">W3Conf</a>, I gave a talk on how the CSS Working Group is attempting to solve the concerns of Web developers with multiple proposals. There are six layout proposals that are relevant to us, all of which I described in the talk:</p>
<p><iframe src="http://www.youtube.com/embed/Y_o0Lv_Mhbw" frameborder="0" width="560" height="315"></iframe></p>
<p>Here is a little more about these proposals and how they will help you in developing websites in the future.</p>
<h3 id="generated_content_for_paged_media">Generated Content For Paged Media</h3>
<ul>
<li><a href="http://dev.w3.org/csswg/css3-gcpm/">W3C Editor’s Draft</a></li>
<li><a href="http://people.opera.com/howcome/2011/reader/">Demo</a></li>
<li>Browser support: Opera Labs Build only</li>
</ul>
<p>This proposal outlines a set of features that would modify the contents of any element to flow as pages, like in a book. A <a href="http://www.youtube.com/watch?v=e_xpbQHtVGE">video demonstration</a> shows how to use paged media to generate HTML5 slideshows (look at the <a href="http://people.opera.com/divyam/pagedcontent/">demos for GCPM</a> in the <a href="http://people.opera.com/howcome/2011/reader/">Opera Labs Build</a> to play with the features more). To make the content of an element be paged, you would use this syntax:</p>
<pre>@media paged {
html {
width: 100%;
overflow-style: paged-x;
padding: 5%;
height: 100%;
box-sizing: border-box;
}
}</pre>
<p>This would make the content look something like this:</p>
<p><img class="aligncenter size-full wp-image-1174" title="layout feature" src="http://www.kabayview.com/wp-content/uploads/2012/01/layout-feature.png" alt="" width="518" height="393" /></p>
<p>Here, <code>@media paged</code> indicates that the browser understands paged media and that all of the selectors specified for it should have their styles applied when paged media is supported. Then, you indicate which selector you want to be paged (in the above example, the selector is the <code>html</code> element itself) by specifying the property <code>overflow-style: paged-x</code>. This will simply make the content paged; if you want paged controls to be visible, you need to specify <code>overflow-style: paged-x-controls</code>.</p>
<p>The properties <code>break-before</code>, <code>break-after</code> <code>break-inside</code> can be used to control where the content falls within the pages. For example, if you want headings to only appear with their corresponding content and never at the end of the page or standing alone, you can specify that:</p>
<pre>h3, h2 {
break-after: avoid;
}</pre>
<p>This ensures that if a heading occurs on the last line of a page, it will be pushed to the next page with the content that it introduces.</p>
<h4 id="api">API</h4>
<p>Two properties are available on an element whose content is paged: <code>currentPage</code> and <code>pageCount</code>. You can set the <code>currentPage</code> property via JavaScript, which would trigger a page change on that element. This would then trigger an <code>onpagechange</code> event on that element, which you could use to run other scripts that are required when the page changes. The <code>pageCount</code> property stores the total number of pages in the paged element. These properties are useful for implementing callbacks that should be triggered on page change; for example, to render notes for a particular slide in a slide deck.</p>
<h3 id="multiple_columns">Multiple Columns</h3>
<ul>
<li><a href="http://dev.w3.org/csswg/css3-multicol/">W3C Editor’s Draft</a></li>
<li><a href="http://people.opera.com/pepelsbey/experiments/multicol/">Demo</a></li>
<li>Browser support: Opera 11.1+, Firefox 2+, Chrome 4+, Safari 3.1+, IE 10+</li>
</ul>
<p>Multiple columns are now available in most browsers (including IE10!), which makes them pretty much ready to use on production websites. You can render the content of any element into multiple columns simply by using <code>column-width: &lt;length unit&gt;</code> or <code>column-count: &lt;number&gt;</code>. As with paged content, you can use <code>break-before</code>, <code>break-after</code> or <code>break-inside</code> to control how the content displays within each column. You can also make one of the child elements span the whole set of columns by using <code>column-span: all</code>. Here is how that would look:</p>
<p><img class="aligncenter size-large wp-image-1176" title="column-span-all" src="http://www.kabayview.com/wp-content/uploads/2012/01/column-span-all-1024x626.png" alt="" width="695" height="424" /></p>
<p>Columns are balanced out with content by default. If you would prefer that columns not be balanced, you can set that by using <code>column-fill: auto</code> property. Here is an example of the default behaviour (i.e. <code>column-fill: balanced</code>):</p>
<p><img class="aligncenter size-full wp-image-1177" title="column-fill-auto" src="http://www.kabayview.com/wp-content/uploads/2012/01/column-fill-auto.png" alt="column fill automatic" width="742" height="278" /></p>
<p>Note that the last column is empty, and each column is filled one after the other.</p>
<h3 id="regions">Regions</h3>
<ul>
<li><a href="http://dev.w3.org/csswg/css3-regions/">W3C Editor’s Draft</a></li>
<li><a href="http://ie.microsoft.com/testdrive/Graphics/hands-on-css3/hands-on_regions.htm">Demo</a></li>
<li>Browser support: IE 10+, Chrome 15+, Safari 6+</li>
</ul>
<p>The closest equivalent to regions would be <a href="http://www.creativepro.com/article/on-the-move-to-indesign-linking-two-text-frames">InDesign’s linking of text frames</a>. With the properties in this proposal, you can make the content of selected elements flow through another set of elements. In other words, your content need not be tied to the document flow any longer.</p>
<p>To begin, you need to select elements whose content will be part of a “named flow,” like this:</p>
<pre>article.news { flow-into: article_flow; }</pre>
<p>Here, all of the content in the <code>article</code> element with the class name <code>news</code> will belong to the flow named <code>article_flow</code>.</p>
<p>Then, you select elements that will render the contents that are part of this named flow:</p>
<pre>#main {
flow-from: article_flow;
}</pre>
<p>Here, the element with the ID <code>main</code> will be used to display the content in the flow named <code>article_flow</code>. This element has now become a region that renders the content of a named flow. Note that any element that is a region establishes new “block-formatting contexts” and “stacking contexts.” For example, if a child element is part of a flow and is absolutely positioned, it will now only be absolutely positioned with respect to the region it belongs to, and not to the whole viewport.</p>
<p>You can also tweak the styles of content that flows through a region:</p>
<pre>@region #main {
p { color: indianred; }
}</pre>
<p><img class="aligncenter size-full wp-image-1180" title="region-styling" src="http://www.kabayview.com/wp-content/uploads/2012/01/region-styling.png" alt="region styling" width="613" height="415" /></p>
<h4 id="interface-api">API</h4>
<p>An interface named <code>getNamedFlow</code> and an event named <code>regionLayoutUpdate</code> are available for elements that are regions.</p>
<h4 id="getnamedflow">getNamedFlow</h4>
<p>This returns the flow that that particular region is associated with. The properties available are:</p>
<ul>
<li><code>overflow</code>A read-only boolean that tells you whether all of the content of the named flow fits within the regions that are part of the flow or whether it overflows.</li>
<li><code>contentNodes</code>A NodeList of all the content elements that belong to the flow.</li>
<li><code>getRegionsByContentNode</code>This returns all of the regions that a particular content element would flow through. A very long paragraph might flow through more than one region; with this method, you can retrieve all of the regions that that paragraph element flows through.</li>
<li><code>regionLayoutUpdate</code>This event gets triggered every time an update is made to the layout of a region. If the region’s dimensions are altered, then the child content elements that are part of that region might alter, too (for example, a few might move to another region, or more child elements might become part of the region).</li>
</ul>
<h3 id="exclusions">Exclusions</h3>
<ul>
<li><a href="http://dev.w3.org/csswg/css3-exclusions/">Draft specification</a> (a combination of two proposals: “Exclusions” and “Positioned Floats”)</li>
<li><a href="http://ie.microsoft.com/testdrive/Graphics/hands-on-css3/hands-on_positionedfloats.htm">Demo</a></li>
<li>Browser support: IE 10+</li>
</ul>
<p>Exclusions allow inline content to be wrapped around or within custom shapes using CSS properties. An element becomes an “exclusion element” when <code>wrap-flow</code> is set to a value that is not <code>auto</code>. It can then set the “wrapping area” for inline text outside or within it, according to various CSS properties. The <code>wrap-flow</code> can take the following values: <code>left</code>, <code>right</code>, <code>maximum</code>,<code>both</code>, <code>clear</code> or the default value of <code>auto</code>. Here is how each of these values would affect the inline content around the exclusion element:</p>
<p><img class="aligncenter size-full wp-image-1182" title="exclusion_wrap_side_auto" src="http://www.kabayview.com/wp-content/uploads/2012/01/exclusion_wrap_side_auto.png" alt="exclusion wrap side auto" width="429" height="342" /></p>
<p><em><code>wrap-flow: auto</code></em></p>
<p><img class="aligncenter size-full wp-image-1181" title="exclusion_wrap_side_right" src="http://www.kabayview.com/wp-content/uploads/2012/01/exclusion_wrap_side_right.png" alt="exclusion wrap side right" width="426" height="347" /></p>
<p><em><code>wrap-flow: right</code></em></p>
<p><img class="aligncenter size-full wp-image-1183" title="exclusion_wrap_side_both" src="http://www.kabayview.com/wp-content/uploads/2012/01/exclusion_wrap_side_both.png" alt="exclusion wrap side both" width="443" height="345" /></p>
<p><em><code>wrap-flow: both</code></em></p>
<p><img class="aligncenter size-full wp-image-1184" title="exclusion_wrap_side_clear" src="http://www.kabayview.com/wp-content/uploads/2012/01/exclusion_wrap_side_clear.png" alt="exclusion wrap side clear" width="425" height="335" /></p>
<p><em><code>wrap-flow: clear</code></em></p>
<p><img class="aligncenter size-full wp-image-1185" title="exclusion_wrap_side_maximum_L" src="http://www.kabayview.com/wp-content/uploads/2012/01/exclusion_wrap_side_maximum_L.png" alt="exclusion wrap side maximum L" width="426" height="348" /></p>
<p><em><code>wrap-flow: maximum</code></em></p>
<p>The <code>wrap-margin</code> property can be used to offset the space between the boundary of the exclusion element and the inline text <em>outside</em> of it. The <code>wrap-padding</code> property is used to offset the space between the boundary of the exclusion element and the inline text <em>inside</em> it.</p>
<p><img class="aligncenter size-full wp-image-1186" title="exclusions_padding_margin" src="http://www.kabayview.com/wp-content/uploads/2012/01/exclusions_padding_margin.png" alt="exclusion padding margin" width="372" height="301" /></p>
<p>In the above image, the space between the content outside of the red dashed circular border and the black text outside of it is determined by the <code>wrap-margin</code>, while the space between the red dashed circular border and the blue text within it is determined by the <code>wrap-padding</code>.</p>
<p>Now comes the fun part: specifying custom shapes for the wrapping area. You can use two properties: <code>shape-outside</code> lets you set the wrapping area for inline text outside of the exclusion element, while <code>shape-inside</code> lets you set the wrapping area for inline text inside the exclusion element.</p>
<p><img class="aligncenter size-full wp-image-1187" title="exclusions-shapes" src="http://www.kabayview.com/wp-content/uploads/2012/01/exclusions-shapes.png" alt="exclusion shapes" width="478" height="399" /></p>
<p>Both of these properties can take SVG-like syntax (<code>circle(50%, 50%, 100px);</code>) or image URLs to set the wrapping area.</p>
<p>Exclusions make magazine-like layouts on the Web a trivial matter and could spark the kind of creative use of content that we are used to seeing in print!</p>
<h3 id="grid">Grid</h3>
<ul>
<li><a href="http://dev.w3.org/csswg/css3-grid-align/">W3C Editor’s Draft</a></li>
<li><a href="http://ie.microsoft.com/testdrive/Graphics/hands-on-css3/hands-on_grid.htm">Demo</a></li>
<li>Browser support: IE 10+</li>
</ul>
<p>Grid properties allow you to throw block-level elements into a grid cell, irrespective of the flow of content within the grid parent element. An element becomes a grid when <code>display</code> is set to <code>grid</code>. You can then set the number of columns and rows with the <code>grid-columns</code> and <code>grid-rows</code> properties, respectively. You can then declare each child selector itself as part of a grid cell, like so:</p>
<pre>#title {
grid-column: 1; grid-row: 1;
}
#score {    grid-column: 2; grid-row: 1;
}</pre>
<p>You can also use a template to plan the grid:</p>
<pre>body {
grid-template: "ta"
"sa"
"bb"
"cc";
}</pre>
<p>In this syntax, each string refers to a row, and each character refers to a grid cell. In this case, the content of grid cell represented by the character <code>a</code> spans two rows but just one column, and the content represented by <code>b</code> spans two columns but just one row.</p>
<p>Now you can set any of the child element’s <code>grid-cell</code> position:</p>
<pre>#title {
grid-cell: 't';
}</pre>
<p>This will make the element with the ID <code>title</code> within the body element to be positioned in the grid cell represented by the character <code>t</code> in the <code>grid-template</code> property.</p>
<p>If you are not using <code>grid-template</code>, you can also declare how many columns or rows a particular element should occupy with the <code>grid-row-span</code> and <code>grid-column-span</code> properties.</p>
<h3 id="flexbox">Flexbox</h3>
<ul>
<li><a href="http://dev.w3.org/csswg/css3-flexbox/">W3C Editor’s Draft</a></li>
<li><a href="http://ie.microsoft.com/testdrive/html5/griddle/default.html">Demo</a></li>
<li>Browser support: WebKit Nightlies</li>
</ul>
<p>Flexbox allows you to distribute child elements anywhere in the box (giving us the much-needed vertical centering), along with flexible units that let you control the fluidity of the child elements’ dimensions.</p>
<p>Note that this specification has changed substantially since it was first proposed. Previously, you would invoke Flexbox for an element with <code>display: box</code>, but now you would use <code>display: Flexbox</code> to do so. Child elements can be vertically aligned to the center with <code>flex-pack: center</code> and horizontally aligned to the center with <code>flex-align: center</code>. Also note that all elements that obey the Flexbox need to be block-level elements.</p>
<h3 id="how_do_various_properties_interact_with_each_other">How Do Various Properties Interact With Each Other?</h3>
<p>You might wonder how to use these properties in combination. The following table shows which of these features can be combined.</p>
<table>
<thead>
<tr>
<th></th>
<th>Paged Media</th>
<th>Multiple Columns</th>
<th>Regions</th>
<th>Exclusions</th>
<th>Grid</th>
<th>Flexbox</th>
</tr>
</thead>
<tbody>
<tr>
<th>Paged Media</th>
<td>✓</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th>Multiple Columns</th>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td></td>
<td></td>
</tr>
<tr>
<th>Regions</th>
<td></td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td></td>
<td></td>
</tr>
<tr>
<th>Exclusions</th>
<td></td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td></td>
<td></td>
</tr>
<tr>
<th>Grid</th>
<td></td>
<td></td>
<td></td>
<td></td>
<td>✓</td>
<td></td>
</tr>
<tr>
<th>Flexbox</th>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>✓</td>
</tr>
</tbody>
</table>
<p>As you can see, the multiple-column properties can be used in conjunction with generated content for paged media, regions and exclusions. <del>But grid, Flexbox and regions are mutually exclusive (i.e. if an element is a grid, it cannot be a Flexbox or region).</del> Do note that, as <a href="http://coding.smashingmagazine.com/2011/12/15/six-css-layout-features-to-look-forward-to/#comment-562612">Alan Stearns says in the comments</a>, while a grid container cannot be a Flexbox or a region, a grid cell could become a region, or a Flexbox child item could be a region.</p>
<h4 id="a_note_before_you_rush_out_to_use_them_in_your_client_projects">A Note Before You Rush Out To Use Them In Client Projects</h4>
<p>The specifications are always changing, so be careful with them. Except for multiple columns, I would recommend using these strictly in personal projects and demos. The syntaxes and properties used in some of the demos are different from what you would find in the actual specifications, because they have changed since the builds that support a previous version of the specification came out. Also, because they are still unstable, all of these properties are vendor-prefixed, which means you have to add support for each prefix as support is added.</p>
<p>If you do use these features, just make sure that the content is readable in browsers that do not support them. The easiest way to do this would be to use <a href="http://modernizr.com/">feature detection</a> and then use CSS to make the content readable when the feature is unsupported.</p>
<h3 id="help_the_working_group">Help The Working Group!</h3>
<p>Do these layout proposals sound exciting to you? Jump on the <a href="http://lists.w3.org/Archives/Public/www-style/">www-style</a> mailing list to provide feedback on them! Just note that the mailing list will flood your inbox, and you should carefully filter the emails so that you pay attention only to the drafts you are interested in.</p>
<p>Write demos and test how these work, and if you find bugs in the builds that have these properties, provide feedback to the browser vendors and submit bug reports. If you have suggestions for changing or adding properties to these proposals, do write in in the mailing list (or you can <a href="https://twitter.com/divya">bug me on Twitter</a>)!</p>
<p>These are exciting times, and within a few years the way we lay out Web pages will have changed dramatically! Perhaps this will finally sound the death knell of print. (Just kidding.)</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.kabayview.com/css3/six-css-layout-features-to-look-forward-to/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>String Handling Functions</title>
		<link>http://www.kabayview.com/php/string-handling-functions</link>
		<comments>http://www.kabayview.com/php/string-handling-functions#comments</comments>
		<pubDate>Mon, 09 Jan 2012 19:01:39 +0000</pubDate>
		<dc:creator>Lynda Damiata</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.kabayview.com/?p=1162</guid>
		<description><![CDATA[&#124; By: James Appleyard &#124; Posted: December 26, 2011 &#124; PHP Tutorials phpmaster.com :: PHP has a vast selection of built-in string handling functions that allow you to easily manipulate strings in almost any possible way. However, learning all these functions, remembering what they do, and when they might come in handy can be a <a href='http://www.kabayview.com/php/string-handling-functions'> [read more]</a>]]></description>
			<content:encoded><![CDATA[<p>| By: <a title="Posts by James Appleyard" href="http://phpmaster.com/author/jappleyard/" rel="author">James Appleyard</a> | Posted: <abbr title="">December 26, 2011</abbr> | <a title="View all posts in PHP Tutorials" href="http://phpmaster.com/category/php-tutorials/" rel="category tag">PHP Tutorials</a><br />
<a href="http://phpmaster.com/" target="_blank">phpmaster.com</a> ::</p>
<p><img class="aligncenter size-full wp-image-1164" title="27442300" src="http://www.kabayview.com/wp-content/uploads/2012/01/27442300.jpg" alt="String Handling Functions" width="616" height="190" />PHP has a vast selection of built-in string handling functions that allow you to easily manipulate strings in almost any possible way. However, learning all these functions, remembering what they do, and when they might come in handy can be a bit daunting, especially for new developers. There is no way I can cover every string function in one article, and besides, that is what the PHP manual is for! But what I will do is show how to work with some of the most commonly used string handling functions that you should know. After this, you’ll be working with strings as well as any concert violinist!</p>
<h2>On the Case</h2>
<p>PHP offers several functions that enable you to manipulate the case of characters within a string without having to edit the string character by character. Why would you care about this? Well maybe you want to ensure that certain text is all in upper case such as acronyms, titles, for emphasis or just to ensure names are capitalized correctly. Or maybe you just want to compare two strings and you want to ensure the letters you are comparing are the same character set. The case manipulation functions are pretty easy to get to grips with; you just pass the string as a parameter to the function and the return value you is the processed string.</p>
<p>If you wanted to ensure all the letters in a specific string were uppercase, you can use the <code>strtoupper()</code> function as follows:</p>
<pre>&lt;?php
$str = "Like a puppet on a string.";
$cased = strtoupper($str);
// Displays: LIKE A PUPPET ON A STRING.
echo $cased;</pre>
<p>It is perhaps obvious but still worth noting that numbers and other non-alphabet characters will not be converted.</p>
<p>As you can probably guess, the <code>strtolower()</code> function does the exact opposite of <code>strtoupper()</code> and converts a string into all lowercase letters:</p>
<pre>&lt;?php
$str = "LIKE A PUPPET ON A STRING.";
$cased = strtolower($str);
// Displays: like a puppet on a string.
echo $cased;</pre>
<p>There may be other times when you want to ensure certain words, such as names or titles, just have the first letter of each word capitalized. For this you can use the <code>ucwords()</code> function:</p>
<pre>&lt;?php
$str = "a knot";
$cased = ucwords($str);
// Displays: A Knot
echo $cased;</pre>
<p>It is also possible to manipulate the case of just the first letter of a string using the <code>lcfirst()</code> and <code>ucfirst()</code> functions. If you want the first letter to be lowercase, use <code>lcfirst()</code>. If you want the first letter to be uppercase, use <code>ucfirst()</code>. The <code>ucfirst()</code> function is probably the most useful since you can use it to ensure a sentence always starts with a capital letter.</p>
<p>&nbsp;</p>
<h2>A Quick Trim</h2>
<p>Sometimes a string needs trimming round the edges. It may have whitespace or other characters at the beginning or end which needs removing. The whitespace can be an actual space character, but it can also be a tab, carriage return, etc. One example of when you might need to do something like this is when you’re working with user input and you want to clean it up it before you start processing it. The <code>trim()</code>function in PHP lets you to do just that; you can pass the string as a parameter and all whitespace from the beginning and end of that string will be removed:</p>
<pre>&lt;?php
$str = "  A piece of string?  ";
// Displays: string(22) " A piece of string? "
var_dump($str);

$trimmed = trim($str);
// Displays: string(18) "A piece of string?"
var_dump($trimmed);</pre>
<p><code>trim()</code> is also multi-purpose in that in addition to the string you can also pass it a set of characters and it will remove any that match from the beginning or end:</p>
<pre>&lt;?php
$str = "A piece of string?";
$trimmed = trim($str, "A?");
// Displays: string(16) " piece of string"
var_dump($trimmed);</pre>
<p>You do need to be careful when you work with these additional characters since <code>trim()</code> will only remove whitespace if you specifically provide it as one of the characters you want removed:</p>
<pre>&lt;?php
$str = "A piece of string?";
$trimmed = trim($str, "A ?");
// Displays: string(15) "piece of string"
var_dump($trimmed);</pre>
<p>Even though <code>trim()</code> only removes characters at the start and end of a string, it has removed both “A” and the space because when “A” is removed the space becomes the new start of the string, and so that is also removed.</p>
<p>There are also <code>ltrim()</code> and <code>rtrim()</code> functions in PHP which are similar to the <code>trim()</code> function but only remove whitespace (or other specified characters) from the left or right of the string respectively.</p>
<h2>How Long is a (Piece of) String?</h2>
<p>Very often when working with strings, you’ll want to know how long it is. For example, when dealing with a form, you may have a field where you want to make sure users can’t go over a certain number of characters. To count the number of characters in a string, you can use the <code>strlen()</code> function:</p>
<pre>&lt;?php
$str = "How long is a piece of string?";
$size = strlen($str);
// Displays: 30
echo $size;</pre>
<h2>Cutting Strings Down to Size</h2>
<p>Another common situation is finding specific text within a given string and “cutting it” out so you can do something else with it. To cut a string down to size, you need a good pair of scissors, and in PHP your scissors are the <code>substr()</code> function.</p>
<p>To use the <code>substr()</code> function, pass the string you want to work with as a parameter along with a positive or negative integer. The number determines where you’ll start cutting the string; 0 starts you off at the first character of the string (remember that when you count through a string, the first character on the left starts at position 0, not 1).</p>
<pre>&lt;?php
$str = "How to cut a string down to size";
$snip = substr($str, 13);
//Displays: string down to size
echo $snip;</pre>
<p>When you use a negative number, <code>substr()</code> will start backwards from the end of the string.</p>
<pre>&lt;?php
$str = "How to cut a string down to size";
$snip = substr($str, -7);
//Displays: to size
echo $snip;</pre>
<p>An optional third parameter to <code>substr()</code> is the length, another integer value that allows you to specify the number of characters you want to extract from the string.</p>
<pre>&lt;?php
$str = "How to cut a string down to size";
$snip = substr($str, 13, 6);
//Displays: string
echo $snip;</pre>
<p>If you just need to find the position of a particular piece of text within a string and nothing else, you can use the <code>strpos()</code> function which returns the position your selection is from the start of the string. A useful trick, especially when you don’t know the starting position of the text you to cut from a string, is to combine the two functions. Rather than specifying a start position as an integer, you can search for a specific piece of text and then extract that.</p>
<pre>&lt;?php
$str = "How to cut a string down to size";
$snip = substr($str, strpos($str, "string"), 6);
//Displays: string
echo $snip;</pre>
<h2>Swap Shop</h2>
<p>Finally, let’s look at replacing a piece of the string with something else, for which you can use <code>str_replace()</code> function. This is ideal for situations where you just want to swap out instances of specific words or a set of characters in a string and replace them with something else:</p>
<pre>&lt;?php
$oldstr = "The cat was black";
$newstr = str_replace("black", "white", $oldstr);
// Displays: The cat was white
echo $newstr;</pre>
<p>You can also provide arrays to <code>str_replace()</code> if you want to replace multiple values:</p>
<pre>&lt;?php
$oldstr  = "The flag was red white and blue.";
$america = array("red", "white", "blue");
$germany = array("black", "red", "yellow");
$newstr = str_replace($america, $germany, $oldstr);
// Displays: The flag was black red and yellow.
echo $newstr;</pre>
<h2>Summary</h2>
<p>Hopefully, this article has given you a taste of some of the things you can do with strings in PHP and made you hungry to learn more. I’ve really barely scraped the tip of the iceberg! The best place to find out more about all of the different string functions is to take some time to read the String Functions page in the PHP Manual.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.kabayview.com/php/string-handling-functions/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Responsive Design Approach for Complex, Multicolumn Data Tables</title>
		<link>http://www.kabayview.com/html5/a-responsive-design-approach-for-complex-multicolumn-data-tables</link>
		<comments>http://www.kabayview.com/html5/a-responsive-design-approach-for-complex-multicolumn-data-tables#comments</comments>
		<pubDate>Mon, 09 Jan 2012 18:17:43 +0000</pubDate>
		<dc:creator>Lynda Damiata</dc:creator>
				<category><![CDATA[HTML5]]></category>
		<category><![CDATA[Responsive Web Design]]></category>

		<guid isPermaLink="false">http://www.kabayview.com/?p=1127</guid>
		<description><![CDATA[Posted by Maggie on 12/29/2011 filamentgroup.com :: In responsive web design, one of the toughest design problems to solve is how format complex tabular data for display on smaller screens. In this post, we&#8217;ll explore an experimental approach to rendering a complex table, using progressive enhancement and responsive design methods, that displays comfortably at a <a href='http://www.kabayview.com/html5/a-responsive-design-approach-for-complex-multicolumn-data-tables'> [read more]</a>]]></description>
			<content:encoded><![CDATA[<p>Posted by Maggie on 12/29/2011<br />
<a href="http://filamentgroup.com/" target="_blank">filamentgroup.com</a> ::</p>
<p><img class="alignleft size-full wp-image-1152" title="dwpe-ad-cover-sml" src="http://www.kabayview.com/wp-content/uploads/2012/01/dwpe-ad-cover-sml.png" alt="Progressice Enhancement" width="97" height="125" />In responsive web design, one of the toughest design problems to solve is how format complex tabular data for display on smaller screens. In this post, we&#8217;ll explore an experimental approach to rendering a complex table, using progressive enhancement and responsive design methods, that displays comfortably at a wide range of screen sizes, provides quick access to the data, and preserves the table structure so that data can still be compared across columns.</p>
<p>We&#8217;ve been batting around the idea of making tables responsive for awhile.</p>
<p>Our initial attempts to make table data palatable on small screens include showing a <a href="http://jsbin.com/apane6/14/">thumbnail image that links to the data</a> or a <a href="http://jsbin.com/emexa4">canvas-based chart</a>; others have developed responsive CSS workarounds that display a definition list, using either <a href="http://jsbin.com/arixic">list</a> or <a href="http://css-tricks.com/responsive-data-tables/">table</a> markup. Which approach to take depends on the type of data. For example, structured data where each row is a unique object or entity—say, business contacts, or favorite Netflix movies—are well-suited to a definition list style on small screens, because header and cell data can be displayed as simple label and value pairs (i.e., Name: Maggie Wachs, Company: Filament Group&#8230;). The switch to a chart or other visualization on smaller screens works well for a simple numeric comparison of a single value. And snapping down to a thumbnail image that launched a full table to pan and zoom was an okay fallback in lieu of no data at all.</p>
<p>But we encountered a scenario that didn&#8217;t quite work with any of the above solutions: a table of complex of financial data with 6-8 related data points, where comparisons and trends among columns are important to see. Visual relationships between headings and cells, and between neighboring columns, are crucial to understanding the data and would be lost on smaller screens if we displayed a list or chart.</p>
<p>We needed a happy medium: a way to keep the basic table structure in place—with headings above, and whole columns that sit side-by-side—and simultaneously display a manageable amount of data at a size that&#8217;s comfortably readable.</p>
<h2>A table for every screen</h2>
<p>The approach we devised starts with a full data set, and uses a simple priority-based class designation to display a manageable subset of data columns for common target screen sizes, and also gives the user control to change column visibility easily.</p>
<p>It&#8217;s probably easier to explain with a concrete example: we&#8217;ll use a table that lists technology companies and their stock prices and several stock performance metrics. Each row displays data for a single company; columns organize data points by type for comparison. <a href="http://filamentgroup.com/examples/rwd-table-patterns/">View the demo</a>.</p>
<p>All data columns will display on desktops and tablets in landscape orientation, but only a subset will fit comfortably on anything smaller. So the first order of business is to identify which columns of data are essential to see at all screen widths by default, or optional (shown only when space allows). In our table of tech company stocks, the data is somewhat meaningless without the company name, current stock value, or most recent change, so we&#8217;ll consider those essential. The trade time, previous close, and open values would be nice to see if the screen can fit those columns, so we&#8217;ll make them optional. The remaining data—bid, ask, and 1-year target estimate—are less important in relative terms, so they will appear on only the widest screens.</p>
<p><img class="aligncenter size-full wp-image-1129" title="breakpoints" src="http://www.kabayview.com/wp-content/uploads/2012/01/breakpoints.png" alt="" width="920" height="888" /></p>
<p>In this case, we want users to have the last word regarding which columns to show, so we&#8217;ll also create a custom menu that lets them choose which columns to display:</p>
<p><img class="aligncenter size-full wp-image-1132" title="menu" src="http://www.kabayview.com/wp-content/uploads/2012/01/menu.png" alt="" width="420" height="263" /></p>
<p>&nbsp;</p>
<p>The final result is a table that displays a limited set of columns on smaller screens, and provides quick access to data that&#8217;s hidden because of space constraints (<a href="http://filamentgroup.com/examples/rwd-table-patterns/">view the demo</a>). To accomplish this, we&#8217;ll use progressive enhancement to ensure that we&#8217;re serving a usable experience to all devices. We&#8217;ll start with well-formed, semantic table markup and very basic CSS, and then if the browser is capable, apply JavaScript and enhanced CSS (including media queries) to conditionally show a larger number of columns as screen space allows.</p>
<h2>Markup</h2>
<p>A basic table — with consecutive columns and descriptive headings — is an efficient way to display a complex data set; data arranged into columns and rows are easy to scan and compare. So an HTML table is the clear markup choice for our financial data.</p>
<p>We&#8217;ll start with a well-formed <code>table</code> that contains a <code>thead</code> for the heading row, followed by a <code>tbody</code> for the cells.</p>
<pre>&lt;table cellspacing="0" id="tech-companies"&gt;
&lt;thead&gt;
&lt;tr&gt;
...header cells...
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
...rows of data...
&lt;/tbody&gt;
&lt;/table&gt;</pre>
<p>As we fill in the content, we&#8217;ll add descriptive classes to identify the essential and optional content. We&#8217;ll assign these classes only to the headers; later, we&#8217;ll write a little JavaScript to map these headers to their respective columns of data.</p>
<pre>&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Company&lt;/th&gt;
&lt;th&gt;Last Trade&lt;/th&gt;
&lt;th&gt;Trade Time&lt;/th&gt;
&lt;th&gt;Change&lt;/th&gt;
&lt;th&gt;Prev Close&lt;/th&gt;
&lt;th&gt;Open&lt;/th&gt;
&lt;th&gt;Bid&lt;/th&gt;
&lt;th&gt;Ask&lt;/th&gt;
&lt;th&gt;1y Target Est&lt;/th&gt;
&lt;/tr&gt;
...
&lt;/thead&gt;</pre>
<p>Notice that we added a second class to the Company header, <code>persist</code>. Essential columns are present by default at small screen sizes, but we&#8217;ll still be able to toggle their visibility with the custom menu. Marking the Company column with this class provides a way for us to omit it from the menu, and prevent it from being hidden.</p>
<p>We&#8217;ll complete the table with rows of data that correspond to the column headers:</p>
<pre>&lt;table cellspacing="0" id="tech-companies"&gt;
&lt;thead&gt;
...
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;th&gt;GOOG &lt;span&gt;Google Inc.&lt;/span&gt;&lt;/th&gt;
&lt;td&gt;597.74&lt;/td&gt;
&lt;td&gt;12:12PM&lt;/td&gt;
&lt;td&gt;14.81 (2.54%)&lt;/td&gt;
&lt;td&gt;582.93&lt;/td&gt;
&lt;td&gt;597.95&lt;/td&gt;
&lt;td&gt;597.73 x 100&lt;/td&gt;
&lt;td&gt;597.91 x 300&lt;/td&gt;
&lt;td&gt;731.10&lt;/td&gt;
&lt;/tr&gt;
...
&lt;/tbody&gt;</pre>
<p>Later when we apply JavaScript, we&#8217;ll create a custom menu based on the table&#8217;s content and append it to the page, immediately above the table. The menu will consist of a container element for a &#8220;Display&#8221; button and the menu overlay:</p>
<pre>&lt;div&gt;
&lt;a href="#"&gt;Display&lt;/a&gt;
&lt;div&gt;
...menu content...
&lt;/div&gt;
&lt;/div&gt;</pre>
<p>The menu overlay will contain a list of options, one for each column, where each option has a <code>label</code> and checkbox <code>input</code> for toggling that column&#8217;s visibility (columns with the <code>persist</code> class will be excluded from the menu):</p>
<pre>&lt;div&gt;
&lt;a href="#"&gt;Display&lt;/a&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;input type="checkbox" name="toggle-cols" id="toggle-col-1" value="co-1"&gt;
&lt;label for="toggle-col-1"&gt;Last Trade&lt;/label&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;input type="checkbox" name="toggle-cols" id="toggle-col-2" value="co-2"&gt;
&lt;label for="toggle-col-2"&gt;Trade Time&lt;/label&gt;
&lt;/li&gt;
...
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;</pre>
<p>When the script builds the menu, it will automatically assign <code>name</code> and <code>value</code> attributes and unique IDs to the <code>input</code> elements, and matching <code>for</code> attributes to their labels.</p>
<p>Last but not least, we&#8217;ll wrap the table in a container element to simplify positioning the menu:</p>
<pre>&lt;div&gt;
&lt;table cellspacing="0" id="tech-companies"&gt;
...
&lt;/table&gt;
&lt;/div&gt;</pre>
<h2>CSS</h2>
<p>We&#8217;ll assume you&#8217;re already familiar with using CSS3 media queries to render pages responsively. If not, we highly recommend Ethan Marcotte&#8217;s definitive article, <a href="http://www.alistapart.com/articles/responsive-web-design/">Responsive Web Design</a>, and <a href="http://www.abookapart.com/products/responsive-web-design">book by the same title</a>.</p>
<p>Let&#8217;s start with the table. We want it to fill the available space, so we&#8217;ll assign a width of 100%:</p>
<pre>table {
width: 100%;
font-size: 1.2em;
}</pre>
<p>And then apply color, padding, and alignment properties to make the data easier to scan:</p>
<pre>thead th {
white-space: nowrap;
border-bottom: 1px solid #ccc;
color: #888;
}
th, td {
padding: .5em 1em;
text-align: right;
}
th:first-child,
td:first-child {
text-align: left;
}
tbody th, td {
border-bottom: 1px solid #e6e6e6;
}</pre>
<p>Next, we&#8217;ll write the rules that hide and show columns. We&#8217;ve scoped these styles to a class, <code>enhanced</code>, which is assigned to the table via JavaScript. This ensures that column visibility is altered only when JavaScript is available. By default, we&#8217;ll hide all columns, and show only those marked with the <code>essential</code> class:</p>
<pre>.enhanced th,
.enhanced td {
display: none;
}
.enhanced th.essential,
.enhanced td.essential {
display: table-cell;
}</pre>
<p>Using CSS3 media queries, we&#8217;ll show optional columns when the browser is 500px wide or greater, and all columns at 800px or greater:</p>
<pre>@media screen and (min-width: 500px) {
.enhanced th.optional,
.enhanced td.optional {
display: table-cell;
}
}

@media screen and (min-width: 800px) {
.enhanced th,
.enhanced td {
display: table-cell;
}
}</pre>
<p>When using this approach, how you prioritize and categorize your data must correspond to the number of screen size breakpoints you plan to support. In our example, we&#8217;ve chosen to have two breakpoints, at 500 and 800 pixels wide, and two levels of importance, essential and optional. If we were to add another break point, say around 400px, we would need to rework our categories to include a third (i.e., primary, secondary, tertiary) so that we can mark each column to be visible at a particular breakpoint.</p>
<p>When the custom menu is inserted into the table&#8217;s container, it will appear just above the table on the right:</p>
<pre>.table-menu-wrapper {
position: absolute;
top: -3em;
right: 0;
}</pre>
<p>The menu itself will also be absolutely positioned, and by default will be hidden with the <code>table-menu-hidden</code> class (later, we&#8217;ll write JavaScript to toggle that class when the &#8220;Display&#8221; button is clicked):</p>
<pre>.table-menu {
position: absolute;
right: 0;
left: auto;
background-color: #fff;
padding: 10px;
border: 1px solid #ccc;
font-size: 1.2em;
width: 12em;
}
.table-menu-hidden {
left: -999em;
right: auto;
}</pre>
<p>Finally, we&#8217;ll add relative positioning to the table&#8217;s container. Later, when we append the menu we can position it without having to calculate location coordinates:</p>
<pre>.table-wrapper {
position: relative;
margin: 5em 5%;
}</pre>
<h2>JavaScript</h2>
<p>The table we just created is usable on its own; any browser that renders HTML will display it. With a few JavaScript enhancements, we&#8217;ll be able to view the table at smaller screen sizes without sacrificing the table structure. (The following examples use <a href="http://filamentgroup.com/lab/responsive_design_approach_for_complex_multicolumn_data_tables/jquery.com">jQuery</a>.)</p>
<p>First we&#8217;ll append the <code>enhanced</code> class for scoping styles:</p>
<pre>// add class for scoping styles - cells should be hidden only when JS is on
table.addClass("enhanced");</pre>
<p>We&#8217;ll create a container element for the menu, which will come into play a little later in the script:</p>
<pre><code>var container = $('&lt;div class="table-menu table-menu-hidden"&gt;&lt;ul /&gt;&lt;/div&gt;'); </code></pre>
<p>Then we&#8217;ll enhance the markup with classes and attributes that allow us to control column visibility. We&#8217;ll loop through the table headers and assign them unique IDs, then reference those IDs in <code>headers</code> attributes assigned to associated cells. (The <code><a href="http://www.w3.org/TR/html4/struct/tables.html#adef-headers">headers</a></code> attribute identifies to which header(s) a cell belongs.) We&#8217;ll also copy the classes that we assigned to the column headers — essential and optional — and assign them to the associated columns.</p>
<pre>$( "thead th" ).each(function(i){
var th = $(this),
id = th.attr("id"),
classes = th.attr("class");  // essential, optional (or other content identifiers)

// assign an ID to each header, if none is in the markup
if (!id) {
id = ( "col-" ) + i;
th.attr("id", id);
};

// loop through each row to assign a "headers" attribute and any classes (essential, optional) to the matching cell
// the "headers" attribute value = the header's ID
$( "tbody tr" ).each(function(){
var cell = $(this).find("th, td").eq(i);
cell.attr("headers", id);
if (classes) { cell.addClass(classes); };
});
...</pre>
<p>Next, while still looping through the headers, we&#8217;ll create a menu item for each column, except for those marked with the <code>persist</code> class. Each menu item consists of a checkbox and label with the column header text.</p>
<pre>...
// create the menu hide/show toggles
if ( !th.is(".persist") ) {

// note that each input's value matches the header's ID;
// later we'll use this value to control the visibility of that header and it's associated cells
var toggle = $('&lt;li&gt;&lt;input type="checkbox" name="toggle-cols" id="toggle-col-'+i+'" value="'+id+'" /&gt; &lt;label for="toggle-col-'+i+'"&gt;'+th.text()+'&lt;/label&gt;&lt;/li&gt;');

// append each toggle to the container
container.find("ul").append(toggle);

...</pre>
<p>And then we&#8217;ll bind events to each checkbox for controlling that column&#8217;s visibility.</p>
<pre>...

// assign behavior
toggle.find("input")

// when the checkbox is toggled
.change(function(){
var input = $(this),
val = input.val(),  // this equals the header's ID, i.e. "company"
cols = $("#" + val + ", [headers="+ val +"]"); // so we can easily find the matching header (id="company") and cells (headers="company")

if (input.is(":checked")) { cols.show(); }
else { cols.hide(); };
})

// custom event that sets the checked state for each toggle based on column visibility, which is controlled by @media rules in the CSS
// called whenever the window is resized or reoriented (mobile)
.bind("updateCheck", function(){
if ( th.css("display") ==  "table-cell") {
$(this).attr("checked", true);
}
else {
$(this).attr("checked", false);
};
})

// call the custom event on load
.trigger("updateCheck");

}; // end conditional statement ( !th.is(".persist") )
}); // end headers loop</pre>
<p>After closing the headers loop, we&#8217;ll bind our custom event to the window&#8217;s resize and orientation change events:</p>
<pre>// update the inputs' checked status
$(window).bind("orientationchange resize", function(){
container.find("input").trigger("updateCheck");
});</pre>
<p>And, last but not least, append our checkbox menu to the page and bind show/hide menu events:</p>
<pre>var menuWrapper = $('&lt;div /&gt;'),
menuBtn = $('&lt;a href="#"&gt;Display&lt;/a&gt;');

menuBtn.click(function(){
container.toggleClass("table-menu-hidden");
return false;
});

menuWrapper.append(menuBtn).append(container);
table.before(menuWrapper);  // append the menu immediately before the table

// assign click-away-to-close event
$(document).click(function(e){
if ( !$(e.target).is( container ) &amp;&amp; !$(e.target).is( container.find("*") ) ) {
container.addClass("table-menu-hidden");
}
});</pre>
<h2>Media query support for IE: Respond.js</h2>
<p>Older versions of IE (8 and earlier) don&#8217;t natively support CSS3 media queries, so we need to use a workaround in those browsers to implement our responsive table. Thanks to our own Scott Jehl, we can use a lightweight polyfill script, <a href="https://github.com/scottjehl/Respond">respond.js</a>, that enables support for min- and max-width media query properties. The script is open source and available on <a href="https://github.com/scottjehl/Respond">github</a>.</p>
<h2>Keep the conversation going</h2>
<p>The pattern discussed here is one possibility for coding a responsive table. We hope to discover more, and will update our <a href="https://github.com/filamentgroup/RWD-Table-Patterns">RWD-Table-Patterns</a> git repository as we come across additional use cases.</p>
<p>The demo code shown here is open source and available for download. Feel free to put it through its paces. If you use it and see room for improvement, please submit a pull request and we&#8217;ll review it as soon as possible.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.kabayview.com/html5/a-responsive-design-approach-for-complex-multicolumn-data-tables/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Apply CSS3 Transformations to Background Images</title>
		<link>http://www.kabayview.com/css3/how-to-apply-css3-transformations-to-background-images</link>
		<comments>http://www.kabayview.com/css3/how-to-apply-css3-transformations-to-background-images#comments</comments>
		<pubDate>Thu, 01 Dec 2011 18:03:10 +0000</pubDate>
		<dc:creator>Lynda Damiata</dc:creator>
				<category><![CDATA[CSS3]]></category>

		<guid isPermaLink="false">http://www.kabayview.com/?p=1096</guid>
		<description><![CDATA[By Craig Buckler &#124; October 27, 2011 &#124; sitepoint.com :: Scaling, skewing and rotating any element is possible with the CSS3 transform property. It’s supported in all modern browsers (with vendor prefixes) and degrades gracefully, e.g. #myelement { -webkit-transform: rotate(30deg); -moz-transform: rotate(30deg); -ms-transform: rotate(30deg); -o-transform: rotate(30deg); transform: rotate(30deg); } Great stuff. However, this rotates the <a href='http://www.kabayview.com/css3/how-to-apply-css3-transformations-to-background-images'> [read more]</a>]]></description>
			<content:encoded><![CDATA[<p>By <a title="Posts by Craig Buckler" href="http://www.sitepoint.com/author/craig-buckler/" rel="author">Craig Buckler</a> | October 27, 2011 |<br />
<a href="http://www.sitepoint.com/" target="_blank">sitepoint.com</a> ::</p>
<p>Scaling, skewing and rotating any element is possible with the CSS3 <code>transform</code> property. It’s supported in all modern browsers (with vendor prefixes) and degrades gracefully, e.g.</p>
<pre>#myelement
{
-webkit-transform: rotate(30deg);
-moz-transform: rotate(30deg);
-ms-transform: rotate(30deg);
-o-transform: rotate(30deg);
transform: rotate(30deg);
}</pre>
<p>Great stuff. However, this rotates the whole element — it’s content, border and background image. What if you only want to rotate the background image? Or what if you want the background to remain fixed while the element is rotated?</p>
<p>Currently, there’s no W3C proposal for background-image transformations. It would be incredibly useful so I suspect one will appear eventually, but that doesn’t help developers who want to use similar effects today.</p>
<p>Fortunately, there is a solution. In essence, it’s a hack which applies the background image to a before or after pseudo element rather than the parent container. The pseudo element can then be transformed independently.</p>
<h2>Transforming the Background Only</h2>
<p>The container element can have any styles applied but it must be set to <code>position: relative</code> since our pseudo element will be positioned within it. You should also set <code>overflow: hidden</code> unless you’re happy for the background to spill out beyond the container.</p>
<pre>#myelement
{
position: relative;
overflow: hidden;
}</pre>
<p>We can now create an absolutely-positioned pseudo element with a transformed background. The z-index is set -1 to ensure it appears below the container’s content.</p>
<pre>#myelement:before
{
content: "";
position: absolute;
width: 200%;
height: 200%;
top: -50%;
left: -50%;
z-index: -1;
background: url(background.png) 0 0 repeat;
-webkit-transform: rotate(30deg);
-moz-transform: rotate(30deg);
-ms-transform: rotate(30deg);
-o-transform: rotate(30deg);
transform: rotate(30deg);
}</pre>
<p>Note you may need to adjust the pseudo element’s width, height and position. For example, if you’re using a repeated image, a rotated area must be larger than its container to fully cover the background:</p>
<p><img class="aligncenter size-full wp-image-1097" title="589-transform-background-100pc" src="http://www.kabayview.com/wp-content/uploads/2011/12/589-transform-background-100pc.png" alt="transform background" width="398" height="174" /></p>
<h2>Fixing the Background on a Transformed Element</h2>
<p>All transforms on the parent container are applied to pseudo elements. Therefore, we need to <em>undo</em> that transformation, e.g. if the container is rotated by 30 degrees, the background must be rotated -30 degrees to return to a fixed position:</p>
<pre>#myelement
{
position: relative;
overflow: hidden;
-webkit-transform: rotate(30deg);
-moz-transform: rotate(30deg);
-ms-transform: rotate(30deg);
-o-transform: rotate(30deg);
transform: rotate(30deg);
}
#myelement:before
{
content: "";
position: absolute;
width: 200%;
height: 200%;
top: -50%;
left: -50%;
z-index: -1;
background: url(background.png) 0 0 repeat;
-webkit-transform: rotate(-30deg);
-moz-transform: rotate(-30deg);
-ms-transform: rotate(-30deg);
-o-transform: rotate(-30deg);
transform: rotate(-30deg);
}</pre>
<p>Again, you will need to adjust the size and position to ensure the background covers the parent container adequately.</p>
<p>Please <a href="http://blogs.sitepointstatic.com/examples/tech/background-transform/index.html"><strong>view the demonstration page</strong></a> for examples. The full code is contained in the HTML source.</p>
<p>The effects work in IE9, Firefox, Chrome, Safari and Opera. IE8 will not show any transformations but the background appears.</p>
<p>IE6 and 7 do not support pseudo elements so the background disappears. However, if you want to support those browsers, you could apply a background image to the container then set it to “none” using an advanced selector or conditional CSS.</p>
<p>Full code contained in the HTML source:</p>
<pre>&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="UTF-8" /&gt;
&lt;title&gt;Background Image Transformations&lt;/title&gt;
&lt;style&gt;
body
{
	font-family: arial, helvetica, freesans, sans-serif;
	font-size: 100%;
	color: #333;
	background-color: #ddd;
}

h1
{
	font-size: 1.5em;
	font-weight: normal;
	margin: 0;
}

#element0, #element1, #element2, #element3
{
	width: 12em;
	font-size: 2em;
	text-align: center;
	line-height: 5em;
	margin: 3em auto;
	border: 2px solid #666;
	border-radius: 7px;
}

#element0, #element1
{
	background: url(background.png) 0 0 repeat;
}

#element1, #element3
{
	-webkit-transform: rotate(30deg);
	-moz-transform: rotate(30deg);
	-ms-transform: rotate(30deg);
	-o-transform: rotate(30deg);
	transform: rotate(30deg);
}

#element2, #element3
{
	position: relative;
	overflow: hidden;
}

#element2:before, #element3:before
{
	content: "";
	position: absolute;
	width: 200%;
	height: 200%;
	top: -50%;
	left: -50%;
	z-index: -1;
	background: url(background.png) 0 0 repeat;
}

#element2:before
{
	-webkit-transform: rotate(30deg);
	-moz-transform: rotate(30deg);
	-ms-transform: rotate(30deg);
	-o-transform: rotate(30deg);
	transform: rotate(30deg);
}

#element3:before
{
	-webkit-transform: rotate(-30deg);
	-moz-transform: rotate(-30deg);
	-ms-transform: rotate(-30deg);
	-o-transform: rotate(-30deg);
	transform: rotate(-30deg);
}
&lt;/style&gt;

&lt;/head&gt;
&lt;body&gt;

&lt;h1&gt;Background Image Transformations&lt;/h1&gt;

&lt;div id="element0"&gt;No Transformation&lt;/div&gt;
&lt;div id="element1"&gt;Transformed Element&lt;/div&gt;

&lt;div id="element2"&gt;Transformed Background&lt;/div&gt;

&lt;div id="element3"&gt;Fixed Background&lt;/div&gt;

&lt;p&gt;For more information, please please refer to:&lt;br /&gt;
&lt;a href="<a href="view-source:http://blogs.sitepoint.com/css3-transform-background-image/">http://blogs.sitepoint.com/css3-transform-background-image/</a>"&gt;How to Apply CSS3 Transformations to Background Images&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This example code was developed by &lt;a href="<a href="view-source:http://twitter.com/craigbuckler">http://twitter.com/craigbuckler</a>"&gt;Craig Buckler&lt;/a&gt; of &lt;a href="<a href="view-source:http://optimalworks.net/">http://optimalworks.net/</a>"&gt;OptimalWorks.net&lt;/a&gt; for &lt;a href="<a href="view-source:http://sitepoint.com/">http://sitepoint.com/</a>"&gt;SitePoint.com&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;It can be used without any restrictions but please don't expect 24/7 support! A link back to &lt;a href="<a href="view-source:http://www.sitepoint.com/">http://www.sitepoint.com/</a>"&gt;SitePoint.com&lt;/a&gt; is appreciated.&lt;/p&gt;

&lt;/body&gt;
&lt;/html&gt;</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.kabayview.com/css3/how-to-apply-css3-transformations-to-background-images/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Attaching Files To Your Posts Using WordPress Custom Meta Boxes, Part 2</title>
		<link>http://www.kabayview.com/wordpress/attaching-files-to-your-posts-using-wordpress-custom-meta-boxes-part-2</link>
		<comments>http://www.kabayview.com/wordpress/attaching-files-to-your-posts-using-wordpress-custom-meta-boxes-part-2#comments</comments>
		<pubDate>Thu, 01 Dec 2011 17:39:12 +0000</pubDate>
		<dc:creator>Lynda Damiata</dc:creator>
				<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://www.kabayview.com/?p=1074</guid>
		<description><![CDATA[Tom McFarlin on Oct 25th 2011 &#124; wp.tutsplus.com :: In the first post, we took a look at how to attach a file – specifically, a PDF – to WordPress posts and pages without having to use a plugin or third-party solution. At this point, you can only upload files – there’s no way to <a href='http://www.kabayview.com/wordpress/attaching-files-to-your-posts-using-wordpress-custom-meta-boxes-part-2'> [read more]</a>]]></description>
			<content:encoded><![CDATA[<p><a title="Posts by Tom McFarlin" href="http://wp.tutsplus.com/author/tom/">Tom McFarlin</a> on Oct 25th 2011 |<br />
<a href="http://wp.tutsplus.com/" target="_blank">wp.tutsplus.com</a> ::</p>
<p><a title="Attaching Files To Your Posts Using WordPress Custom Meta Boxes, Part 1" href="http://www.kabayview.com/wordpress/attaching-files-to-your-posts-using-wordpress-custom-meta-boxes-part-1">In the first post</a>, we took a look at how to attach a file – specifically, a PDF – to WordPress posts and pages without having to use a plugin or third-party solution. At this point, you can only upload files – there’s no way to actually deactivate the link or delete the link to the file once it has been uploaded. In this post, we’ll take a look at how to provide some slightly better styling for the download link and how to extend the custom meta box functionality by allowing users to delete files after they’ve downloaded them.</p>
<p>&nbsp;</p>
<hr />
<h2>Dress It Up</h2>
<p>If you followed along with the code in the first post, then you should have a functional demo of how attaching a PDF to a WordPress post (or page) works; however, the overall presentation doesn’t look very good:</p>
<p><img class="aligncenter size-full wp-image-1075" title="figure_0" src="http://www.kabayview.com/wp-content/uploads/2011/12/figure_0.png" alt="figure example" width="779" height="256" /></p>
<p>Before going any further, let’s clean this up a bit so that it looks a bit more integrated with the default theme. Remember that we’re using <a href="http://theme.wordpress.com/themes/twentyeleven/">Twentyeleven</a> as our default theme so that we’re all on the same page as we work through the tutorial.</p>
<p>First, let’s move the download link into a more logical location. If you’ve been following along since the first post, you’ll recall that we placed the download link in single.php which is located in the root of the theme directory. Open the file and locate the block of code that looks like this:</p>
<pre>get_template_part( 'content', 'single' );
$doc = get_post_meta(get_the_ID(), 'wp_custom_attachment', true);

&lt;a href="    &lt;?php echo $doc['url']; ?&gt;"&gt;
Download PDF Here
&lt;/a&gt;</pre>
<p>Copy all but the first line of code and remove it from the file. This should leave only a call to <a href="http://codex.wordpress.org/Function_Reference/get_template_part">get_template_part</a>.</p>
<p>Next, locate custom-single.php. This is a template file located in the root of the theme directory. Find the call to <a href="http://codex.wordpress.org/Function_Reference/the_content">the_content()</a> and then paste the code you just copied directly below it. This should result in the following block of code:</p>
<pre>the_content();
$doc = get_post_meta(get_the_ID(), 'wp_custom_attachment', true);
&lt;a href="    &lt;?php echo $doc['url']; ?&gt;"&gt;
Download PDF Here
&lt;/a&gt;</pre>
<p>Now, let’s wrap the link in a container so that we can easily style it. I’m giving my container the ID of ‘wp_custom_attachment.’ Feel free to use whatever you like, just remember to refer to it correctly in your stylesheet.</p>
<p>Here’s my markup:</p>
<pre>the_content();
$doc = get_post_meta(get_the_ID(), 'wp_custom_attachment', true);
&lt;div id="wp_custom_attachment"&gt;
&lt;a href="&lt;!--?php echo $doc['url']; ?--&gt;"&gt;
Download PDF Here
&lt;/a&gt;
&lt;/div&gt;&lt;!-- #wp_custom_attachment --&gt;</pre>
<p>And here’s my CSS:</p>
<pre>.wp_custom_attachment {
margin: 8px 0 8px 0;
border: 1px solid #DDD;
background: #EEE;
padding: 8px;
text-align: center;
border-radius: 4px;
}</pre>
<p>Permitting you’ve written everything correctly, the download link should now look like this:</p>
<p><img class="aligncenter size-full wp-image-1082" title="figure_1" src="http://www.kabayview.com/wp-content/uploads/2011/12/figure_1.png" alt="example figure 1" width="660" height="240" /></p>
<p>Much better, right? It’s now styled such that it looks to be more tightly integrated with the theme. Remember to make the corresponding changes to page.php, as well (considering that we’re supporting file attachments on both posts and pages).</p>
<hr />
<h2>Download, When Available</h2>
<p>Before moving on, we have one more small change to make to the code we just added. Right now, the download link is displayed unconditionally. This means that whether or not a post actually has a file, we’re displaying the download link.</p>
<p>Ideally, we only want to display the download link whenever there is a file to download. As such, we’ll need a conditional. Specifically, we’ll need to get the associated post meta data, determine if there is an actual URL for the file attachment. If so, we’ll display the link; otherwise, we won’t.</p>
<p>In the block of code we just added to content-single.php, place an opening if statement just above the opening wp_custom_attachment tag and close the statement just below the closing container tag. Right now, the code should look something like this:</p>
<pre>the_content();
$doc = get_post_meta(get_the_ID(), 'wp_custom_attachment', true);
if() {
&lt;div id="wp_custom_attachment"&gt;
&lt;a href="&lt;!--?php echo $doc['url']; ?--&gt;"&gt;
Download PDF Here
&lt;/a&gt;
&lt;/div&gt;&lt;!-- #wp_custom_attachment --&gt;
} // end if</pre>
<p>We need to check the presence of the document’s URL. There are a number of ways to do this, but I typically check by taking a look at its URL attribute. The resulting code block is:</p>
<pre>the_content();
$doc = get_post_meta(get_the_ID(), 'wp_custom_attachment', true);
if(strlen(trim($doc['url'])) &gt; 0) {
&lt;div id="wp_custom_attachment"&gt;
&lt;a href="&lt;!--?php echo $doc['url']; ?--&gt;"&gt;
Download PDF Here
&lt;/a&gt;
&lt;/div&gt;&lt;!-- #wp_custom_attachment --&gt;
} // end if</pre>
<p>At this point, the download link should only display when there is a valid file attached to the give post or page. Try it out.</p>
<hr />
<h2>Deleting The File</h2>
<p>At this point, we’ve tied up some loose ends from the previous post and we’re ready to finish up the functionality necessary to delete attachments.</p>
<h3>Laying The Foundation</h3>
<p>Recall from the last post that once the user attempts to upload a file, we have a serialization function that fires that’s responsible for actually writing the file to disk. For reference, this takes place in save_custom_meta_data.</p>
<p>In order to properly delete a file, we need to track the existing file’s location and whether or not a user has actually requested to delete the file. We’ll do that with a combination of an input box and an anchor.</p>
<p>First, locate the ‘wp_custom_attachment’ function that we created in the last post. This is where we added the file input element. Just below the input element add the following code (the full function will be provided below):</p>
<pre>// Create the input box and set the file's URL as the text element's value
$html .= '&lt;input type="text" id="wp_custom_attachment_url" name="wp_custom_attachment_url" value=" ' . $doc['url'] . '" size="30" /&gt;';</pre>
<p>This will add an a text input element which tracks the value of the uploaded document’s URL. We’ll clean this up a bit later in the tutorial, but for now, let’s introduce an an anchor for deleting the file. Just below the two lines of code we just added, write the following:</p>
<pre>$html .= '&lt;a href="javascript:;" id="wp_custom_attachment_delete"&gt;' . __('Delete File') . '&lt;/a&gt;';</pre>
<p>&nbsp;</p>
<p>Take note: we’ve given the anchor a unique ID. This will be necessary when we begin hooking up the administration area to handle user events. If you don’t give your anchor this ID, make note of whatever you do assign.</p>
<p>We’re not quite done yet. Remember how we setup the single post and page views to conditionally display the download link? We need to do the same thing for the delete link. Specifically, we need to only show the delete link if a document exists. So, in similar fashion, wrap the anchor in a conditional statement that checks for the presence of the document’s URL:</p>
<pre>// Display the 'Delete' option if a URL to a file exists
if(strlen(trim($doc['url'])) &gt; 0) {
$html .= '&lt;a href="javascript:;" id="wp_custom_attachment_delete"&gt;' . __('Delete File') . '&lt;/a&gt;';
} // end if</pre>
<p>It’s nothing too heavy, right? To be complete, here’s the full function as it stands:</p>
<pre>function wp_custom_attachment() {

wp_nonce_field(plugin_basename(__FILE__), 'wp_custom_attachment_nonce');

$html = '
&lt;p&gt;';
$html .= 'Upload your PDF here.';
$html .= '&lt;/p&gt;';
$html .= '&lt;input type="file" id="wp_custom_attachment" name="wp_custom_attachment" value="" size="25" /&gt;';

// Grab the array of file information currently associated with the post
$doc = get_post_meta(get_the_ID(), 'wp_custom_attachment', true);

// Create the input box and set the file's URL as the text element's value
$html .= '&lt;input type="text" id="wp_custom_attachment_url" name="wp_custom_attachment_url" value=" ' . $doc['url'] . '" size="30" /&gt;';

// Display the 'Delete' option if a URL to a file exists
if(strlen(trim($doc['url'])) &gt; 0) {
$html .= '&lt;a href="javascript:;" id="wp_custom_attachment_delete"&gt;' . __('Delete File') . '&lt;/a&gt;';
} // end if

echo $html;

} // end wp_custom_attachment
&lt;/p&gt;</pre>
<p>We’ll revisit this function a little but later in the tutorial but, for now, test it out. First, navigate to a post that has no attachment. You should see the file input box and an empty input box. After uploading a file, you should see the input box contain the URL of the file followed by a link for deleting the file.</p>
<p>But we’re not done yet. After all, the delete link doesn’t actually do anything.</p>
<h3>Wiring It Up</h3>
<p>Next, locate the ‘js’ directory in the theme root. Add a new file called custom_attachment.js. We’ll write code for this momentarily, but the purpose of the file will be what allows us to actually delete the PDF that we’ve attached to a post.</p>
<p>After that, open up functions.php and add the following function at the end of the file:</p>
<pre>function add_custom_attachment_script() {

wp_register_script('custom-attachment-script', get_stylesheet_directory_uri() . '/js/custom_attachment.js');
wp_enqueue_script('custom-attachment-script');

} // end add_custom_attachment_script
add_action('admin_enqueue_scripts', 'add_custom_attachment_script');</pre>
<p>This function will read the JavaScript file that we just created and include it on any administrative page in the WordPress backend. Enqueuing and Registering scripts is beyond the scope of the tutorial, but I recommend <a href="http://codex.wordpress.org/Function_Reference/wp_enqueue_script">reading up on it</a>.</p>
<p>Next, let’s revisit the JavaScript file. Generally speaking, the code should do the following things:</p>
<ul>
<li>Determine if the delete link is present</li>
<li>If the link is present, attach a custom event handler that clears out the text input that contains the URL of the file</li>
<li>Hide the link once the file has been marked for deletion</li>
</ul>
<p>The source code is below and it has been fully commented to help explain what each line is doing:</p>
<pre>jQuery(function($) {

// Check to see if the 'Delete File' link exists on the page...
if($('a#wp_custom_attachment_delete').length === 1) {

// Since the link exists, we need to handle the case when the user clicks on it...
$('#wp_custom_attachment_delete').click(function(evt) {

// We don't want the link to remove us from the current page
// so we're going to stop it's normal behavior.
evt.preventDefault();

// Find the text input element that stores the path to the file
// and clear it's value.
$('#wp_custom_attachment_url').val('');

// Hide this link so users can't click on it multiple times
$(this).hide();

});

} // end if

});</pre>
<p>At this point, the file will not be deleted but you should have a functional view. Locate a page that has a file attached to it. Your custom meta box should look something like this:</p>
<p><img class="aligncenter size-full wp-image-1089" title="figure_2" src="http://www.kabayview.com/wp-content/uploads/2011/12/figure_2.png" alt="figure example 2" width="298" height="152" />After clicking on the ‘Delete Link’ anchor, the custom meta box should look like this:</p>
<p><img class="aligncenter size-full wp-image-1090" title="figure_3" src="http://www.kabayview.com/wp-content/uploads/2011/12/figure_3.png" alt="example figure 3" width="301" height="146" /></p>
<p>If not, double-check your debugging console to verify that you don’t have any JavaScript errors.</p>
<hr />
<h2>Deleting The File</h2>
<p>At this point, we’ve done all but actually delete the file. To do this, we’ll need to update the save_custom_meta_data function that we wrote in the first post. Recall that the functional includes a conditional checks the contents of the $_FILES collection coming from the POST request. If the collection is populated, then we serialization the file.</p>
<p>Since we’re attempting to delete the file, the $_FILES collection shouldn’t contain any data so all of our code will need to be contained in an else clause. The full source code for the function will be provided below, but here’s how the functional should work:</p>
<ul>
<li>Check to see if there’s a document associated with the post</li>
<li>Check to see if the text box used for tracking the file’s URL is empty</li>
<li>If a file exists and the text box is empty, delete the file and update the associated meta data</li>
</ul>
<p>This should be straightforward: We’ve given each post a text element that contains the URL to the file. If the file URL is empty, it means the user has clicked on the ‘Delete File’ link and is requesting to delete the file. Here’s how we can achieve just that:</p>
<pre>// Grab a reference to the file associated with this post
$doc = get_post_meta($id, 'wp_custom_attachment', true);

// Grab the value for the URL to the file stored in the text element
$delete_flag = get_post_meta($id, 'wp_custom_attachment_url', true);

// Determine if a file is associated with this post and if the delete flag has been set (by clearing out the input box)
if(strlen(trim($doc['url'])) &gt; 0 &amp;&amp; strlen(trim($delete_flag)) == 0) {

// Attempt to remove the file. If deleting it fails, print a WordPress error.
if(unlink($doc['file'])) {

// Delete succeeded so reset the WordPress meta data
update_post_meta($id, 'wp_custom_attachment', null);
update_post_meta($id, 'wp_custom_attachment_url', '');

} else {
wp_die('There was an error trying to delete your file.');
} // end if/el;se

} // end if</pre>
<p>Once the file is deleted, note that we also have to update the post meta data by emptying out the attachment’s value as well as the attachment’s URL value. In the odd case that the file doesn’t delete, we’re displaying a simple error message. Advanced error handling is beyond the scope of this post.</p>
<p>As promised, here’s the full serialization function:</p>
<pre>function save_custom_meta_data($id) {

/* --- security verification --- */
if(!wp_verify_nonce($_POST['wp_custom_attachment_nonce'], plugin_basename(__FILE__))) {
return $id;
} // end if

if(defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE) {
return $id;
} // end if

if(!current_user_can('edit_page', $id)) {
return $id;
} // end if
/* - end security verification - */

// Make sure the file array isn't empty
if(!emptyempty($_FILES['wp_custom_attachment']['name'])) {

// Setup the array of supported file types. In this case, it's just PDF.
$supported_types = array('application/pdf');

// Get the file type of the upload
$arr_file_type = wp_check_filetype(basename($_FILES['wp_custom_attachment']['name']));
$uploaded_type = $arr_file_type['type'];

// Check if the type is supported. If not, throw an error.
if(in_array($uploaded_type, $supported_types)) {

// Use the WordPress API to upload the file
$upload = wp_upload_bits($_FILES['wp_custom_attachment']['name'], null, file_get_contents($_FILES['wp_custom_attachment']['tmp_name']));

if(isset($upload['error']) &amp;&amp; $upload['error'] != 0) {
wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
} else {
add_post_meta($id, 'wp_custom_attachment', $upload);
update_post_meta($id, 'wp_custom_attachment', $upload);
} // end if/else

} else {
wp_die("The file type that you've uploaded is not a PDF.");
} // end if/else

} else {

// Grab a reference to the file associated with this post
$doc = get_post_meta($id, 'wp_custom_attachment', true);

// Grab the value for the URL to the file stored in the text element
$delete_flag = get_post_meta($id, 'wp_custom_attachment_url', true);

// Determine if a file is associated with this post and if the delete flag has been set (by clearing out the input box)
if(strlen(trim($doc['url'])) &gt; 0 &amp;&amp; strlen(trim($delete_flag)) == 0) {

// Attempt to remove the file. If deleting it fails, print a WordPress error.
if(unlink($doc['file'])) {

// Delete succeeded so reset the WordPress meta data
update_post_meta($id, 'wp_custom_attachment', null);
update_post_meta($id, 'wp_custom_attachment_url', '');

} else {
wp_die('There was an error trying to delete your file.');
} // end if/el;se

} // end if

} // end if/else

} // end save_custom_meta_data
add_action('save_post', 'save_custom_meta_data');</pre>
<p>By now, you’ve got a fully functioning custom meta box. Give it a try.</p>
<hr />
<h2>Cleaning It Up</h2>
<p>We’ve got one last minor change to make just to make our UI complete. Remember the text input that we added earlier in the tutorial that’s responsible for maintaining the file’s URL? We can mark that as hidden – there’s no reason the user needs to see it. The JavaScript source will still use it properly and its value will be read in the serialization function.</p>
<p>The final wp_custom_attachment function should look like this:</p>
<pre>function wp_custom_attachment() {

wp_nonce_field(plugin_basename(__FILE__), 'wp_custom_attachment_nonce');

$html = '&lt;p&gt;';
$html .= 'Upload your PDF here.';
$html .= '&lt;/p&gt;';
$html .= '&lt;input type="file" id="wp_custom_attachment" name="wp_custom_attachment" value="" size="25" /&gt;';

// Grab the array of file information currently associated with the post
$doc = get_post_meta(get_the_ID(), 'wp_custom_attachment', true);

// Create the input box and set the file's URL as the text element's value
$html .= '&lt;input type="hidden" id="wp_custom_attachment_url" name="wp_custom_attachment_url" value=" ' . $doc['url'] . '" size="30" /&gt;';

// Display the 'Delete' option if a URL to a file exists
if(strlen(trim($doc['url'])) &gt; 0) {
$html .= '&lt;a href="javascript:;" id="wp_custom_attachment_delete"&gt;' . __('Delete File') . '&lt;/a&gt;';
} // end if

echo $html;

} // end wp_custom_attachment</pre>
<p>These two posts covered a lot of information. There are a number of canned solutions – be it plugins, themes, or other add-ons – available for integrating functionality like this, but part of being a good developer is knowing when to use a third-party solution and when to roll your own.</p>
<p>Additionally, if you’re working with WordPress in a professional capacity, then it’s important to understand the API. Hopefully this series has helped showcase much of what can be done by leveraging core functionality of WordPress.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.kabayview.com/wordpress/attaching-files-to-your-posts-using-wordpress-custom-meta-boxes-part-2/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Responsive IMGs Part 2 — In-depth Look at Techniques</title>
		<link>http://www.kabayview.com/responsive-web-design/responsive-imgs-part-2-%e2%80%94-in-depth-look-at-techniques</link>
		<comments>http://www.kabayview.com/responsive-web-design/responsive-imgs-part-2-%e2%80%94-in-depth-look-at-techniques#comments</comments>
		<pubDate>Tue, 15 Nov 2011 14:42:50 +0000</pubDate>
		<dc:creator>Lynda Damiata</dc:creator>
				<category><![CDATA[Responsive Web Design]]></category>

		<guid isPermaLink="false">http://www.kabayview.com/?p=1061</guid>
		<description><![CDATA[September 30th, 2011 by Jason Grigsby &#124; cloudfour.com :: In Responsive IMGs Part 1, I took a high-level look at what responsive IMGs are, the problem they are trying to solve, and the common issues they face. In this post, I’m going to take a deeper look at the specific techniques being used to provide <a href='http://www.kabayview.com/responsive-web-design/responsive-imgs-part-2-%e2%80%94-in-depth-look-at-techniques'> [read more]</a>]]></description>
			<content:encoded><![CDATA[<p>September 30th, 2011 by Jason Grigsby |<br />
<a href="http://www.cloudfour.com/" target="_blank">cloudfour.com</a> ::</p>
<p>In <a title="Responsive IMGs — Part 1" href="http://www.kabayview.com/responsive-web-design/responsive-imgs-%e2%80%94-part-1" target="_blank">Responsive IMGs Part 1</a>, I took a high-level look at what responsive IMGs are, the problem they are trying to solve, and the common issues they face. In this post, I’m going to take a deeper look at the specific techniques being used to provide responsive IMGs and try to evaluate what works and doesn’t. If you haven’t read <a title="Responsive IMGs — Part 1" href="http://www.kabayview.com/responsive-web-design/responsive-imgs-%e2%80%94-part-1" target="_blank">part 1</a>, you may want to do so before reading this post as it will help explain some of the terms I use.</p>
<p>When I started working on this project two months ago, I thought I would get to the end and be able to say, “Here are the three approaches that work best. Go download them and figure out how to integrate them into your systems.” Oh naivety!</p>
<p>What I’ve found is that there is no comprehensive solution. Instead, we have several months of experiments. Each experiment has its own advantages and disadvantages.</p>
<p>Because of this, the best thing we can do is understand the common elements and challenges so that we can start to pick the best parts of each for building our own solutions.</p>
<p>So um… this is a long post. Sorry.</p>
<h2>Abandoned approaches</h2>
<h3>Dynamic Base Tag</h3>
<p>Many of the early techniques used javascript to dynamically change the base tag. The new base tag would add directories into the path that would be used to indicate what size image should be retrieved. After the document loaded, the base tag would be removed.</p>
<p>Unfortunately, this approach ran into race conditions that I described in part 1. I found that Google Chrome was downloading both the mobile and desktop images. <a href="http://twitter.com/scottjehl">Scott Jehl</a> found the problem to be a difference between how inline and external javascript is handled. He submitted a <a href="https://bugs.webkit.org/show_bug.cgi?id=66474" target="_blank">bug</a> to webkit which has been marked as “won’t fix” because:</p>
<blockquote><p>Inserting base element effectively changes all the subsequent URLs on the page. Any script may insert one so to avoid double loads we could never load anything else as long as there is a pending script load. This would mean disabling preloading, which is out of the question.</p></blockquote>
<p>In theory, you could still use a dynamic base tag inline, but the Filament Group has been primarily using a cookies-based approach instead which seems safer.</p>
<h3>Temporary images</h3>
<p>Another early technique was to have the src of imgs pointing to a temporary image and then having javascript replace the source with the correct file path. In most cases, the image was an one pixel transparent gif set up with caching which would hopefully prevent the browser from requesting it more than once no matter how many times it was referenced in the page.</p>
<p>The problem with this technique is that if javascript isn’t present, the browser will never download the images.</p>
<h2 id="js-based">Javascript-based solutions</h2>
<h3 id="altpaths">Where do you store the path to alternate versions of an image?</h3>
<p>If the the img points to ‘small.jpg’, where do you put the information that ‘large.jpg’ is what should be loaded on larger screens?</p>
<h4 id="url_parameters">URL parameters</h4>
<p>One solution is to put the path to alternate versions of the image in the src attribute as url parameters. In its simplest form:</p>
<p><code>&lt;img src="small.jpg?full=large.jpg"&gt;</code></p>
<p>If you have multiple sizes of images, they simply get added as additional values on the url. The key to making this work is coupling it with an .htaccess file.</p>
<h5>Potential CDN, proxies, and caching issues</h5>
<p>The big drawback to using URL parameters is that it may cause problems with content deliver networks and proxies that doesn’t pay attention to url parameters when caching content. Some caching algorithms ignore anything that has a URL parameter on it which means that pages will slow down because images aren’t cached.</p>
<p>Others will simply cache the first version of the image they see. If the first person behind a proxy cache happened to view the page on a mobile phone, then every subsequent user sees the mobile size image until the cache expires.</p>
<p>How likely is this to be an issue? I had the same question so I asked Steve Souders. He says that it is <a href="http://twitter.com/#%21/souders/status/118912008098811905">enough of a problem that you can’t ignore it</a>. This echoes comments by Bryan and Stephanie Rieger at Breaking Development about problems with caching and CDNs.</p>
<p>Therefore, I think we should be looking for techniques that don’t use url parameters.</p>
<h5>Examples of this approach:</h5>
<ul>
<li><a href="https://github.com/filamentgroup/Responsive-Images">Responsive Images JS Master Branch</a></li>
<li><a href="https://github.com/allmarkedup/responsive-images-alt">Responsive images alt</a></li>
<li><a href="http://www.craig-russell.co.uk/responsive-images-and-context-aware-image-sizing/">Responsive Images and Context Aware Sizing</a></li>
<li><a href="http://www.grahambird.co.uk/lab/doubletake/">Responsive images with Doubletake.js</a></li>
<li><a href="http://www.jamesfairhurst.co.uk/posts/view/responsive_images_with_php_and_jquery/">Responsive images with PHP and jQuery</a></li>
<li><a href="http://blog.keithclark.co.uk/responsive-images-using-cookies/">Responsive images using cookies</a></li>
<li><a href="https://github.com/ahume/Responsive-Images">Context aware responsive images</a></li>
</ul>
<p><a name="data-attributes"></a><a name="toc-anchor-1977-9"></a></p>
<h4 id="data-attributes">Data attributes</h4>
<p>Instead of putting the file path into the url parameters, the information is put in one or more data- attributes. For example:</p>
<blockquote><p>&lt;img src=”small.r.jpg” data-fullsrc=”large.jpg”&gt;</p></blockquote>
<p>Which element has data attributes added to it and how many are added depends on the technique.</p>
<h5>Looping through every img tag</h5>
<p>The only disadvantage to this technique that I’m aware of is the fact that the javascript has to loop through every image, check for data attributes, and then modify the src attribute depending on screen size. This is probably not a big problem on desktop browsers which is where the loop is mostly to be used.</p>
<h5>Examples of this approach</h5>
<ul>
<li><a href="https://github.com/filamentgroup/Responsive-Images/tree/data-attribute-based">Responsive Images JS data-attribute-based branch</a></li>
<li><a href="http://www.monoliitti.com/images/">Testing Responsive Images</a></li>
<li><a href="http://www.headlondon.com/our-thoughts/technology/posts/creating-responsive-images-using-the-noscript-tag">Creating responsive images using the noscript tag</a></li>
</ul>
<h4 id="filestructure">Assumed file structure</h4>
<p>In this variation, the file path isn’t included in the HTML document. Instead, it is assumed that the images are put on the server in a regular fashion. For example, all small images might be in /images/sml/ whereas large images are in /images/lrg/.</p>
<p>If this is true, then the html doesn’t need to provide both paths. It just needs to provide the image filename (e.g., boat.jpg) and then let javascript modify the src to be appropriate for the size of the screen (/images/lrg/boat.jpg for desktop).</p>
<h5>Examples of this approach</h5>
<ul>
<li><a href="https://github.com/allmarkedup/responsive-images-alt">responsive-images-alt</a></li>
<li><a href="http://adaptive-images.com/">Adapative images</a></li>
</ul>
<h4 id="dynamic-filenames">Dynamic file names</h4>
<p>One of the things that I suggested in part 1 was that we might need arbitrary image sizes. Some of the solutions are built around the assumption that you can pass the dimensions that you want in the url and get back an image at that size.</p>
<p>Because the images are resized on the fly, there is no need to store alternative file paths in the HTML document. Javascript will modify the filename from something like ‘boat.jpg’ to ‘boat-480×200.jpg’. There is no issue with caching or CDNs because each image is unique.</p>
<h5>Some images cannot simply be resized</h5>
<p>This approach doesn’t provide a good solution for manually choosing images at different sizes. It assumes that resizing images will work in all cases which we know is not true.</p>
<h5>Examples of this approach</h5>
<ul>
<li><a href="https://github.com/filamentgroup/Responsive-Images/tree/meaningful-base">Responsive Images JS meaningful branch</a></li>
<li><a href="http://blog.trasatti.it/2011/05/responsive-images-and-tinysrc.html">Responsive images and tinySrc</a></li>
</ul>
<h3 id="htaccess">Role of .htaccess (or similar rewrite rules)</h3>
<p>Many of the solutions rely on server rewrite rules. The examples are usually written using Apache .htaccess files, but they could be any sort of rewrite rule.</p>
<p>Lets look at a snippet of the .htaccess file from <a href="https://github.com/filamentgroup/Responsive-Images/tree/cookie-driven">Responsive Images JS cookie-based branch</a> to see how rewrite rules are being used:</p>
<p><code>RewriteEngine On<br />
#large cookie, large image<br />
RewriteCond %{HTTP_COOKIE} rwd-screensize=large<br />
RewriteCond %{QUERY_STRING} large=([^&amp;]+)<br />
RewriteRule .* %1 [L]<br />
</code></p>
<p>The first line turns rewrite rules on. Next comes a couple of conditions (RewriteCond). The first checks to see if there is a cookie called rwd-screensize that has the value of large. The second checks to see if the query string for the url contains a value for large. This .htaccess file is looking for something like:</p>
<p><code>&lt;img src="small.jpg?large=large.jpg"&gt;</code></p>
<p>If both conditions are met—the cookie is set to large and there is a large value in the query string—then the rewrite rule will send the file that was specified in the query string (in the example above, that would be large.jpg).</p>
<p>The rwd-screensize cookie is set by javascript after it tests for the screen size.</p>
<h3 id="preventdownload">How do you prevent the browser from downloading multiple images?</h3>
<p>With the basics out of the way, we can now get to the tricky part. As mentioned in part 1, intercepting the browser before it starts downloading images so that you can evaluate and possibly change the source of those images is tricky and may result in race conditions.</p>
<p>Now that the dynamic base tag has been ruled out, there are two main techniques that remain.</p>
<h4 id="cookies">Set a cookie</h4>
<p>This is the method that the Filament Group settled on for the Boston Globe. Javascript is inserted into the head of the document so that it evaluates as soon as possible.</p>
<p>After it determines the screen size, it sets a cookie. Every subsequent image request sent from the browser will include the cookie. The server can use the cookie to determine the best image to sent back to the user.</p>
<h5>Potential problems</h5>
<p>If the browser doesn’t support cookies or the user blocks them, then the javascript will have no effect.</p>
<p>Also, Yoav Weiss has done some testing and <a href="http://blog.yoav.ws/2011/09/Preloaders-cookies-and-race-conditions">shared results</a> that indicate that duplicate files will be downloaded by IE9. Firefox will download duplicate files if the script is external, but not if it internal. This suggests that cookies may also be subject to the race condition problem that caused us to abandon the dynamic base tag approach.</p>
<h5>Examples of this approach</h5>
<ul>
<li><a href="https://github.com/filamentgroup/Responsive-Images/tree/cookie-driven">Responsive Images cookie branch</a></li>
<li><a href="http://blog.keithclark.co.uk/responsive-images-using-cookies/">Responsive images using cookies</a></li>
<li><a href="https://github.com/allmarkedup/responsive-images-alt">responsive-images-alt</a></li>
</ul>
<h4 id="noscript">Noscript tag</h4>
<p>Within the last couple of months, new techniques have emerged that use the noscript tag as a way to prevent extra downloads. The first post I saw describing this technique was by <a href="https://twitter.com/#%21/tiny_m">Mairead Buchan</a>. She describe it as having “<a href="http://www.headlondon.com/our-thoughts/technology/posts/creating-responsive-images-using-the-noscript-tag"> the elegance of a wading hippo</a>”. Despite that description, I think this technique holds promise.</p>
<p>A <a href="http://www.monoliitti.com/images/">cleaner implementation of the noscript approach</a> was created independently by <a href="http://twitter.com/#%21/apeisa">Antti Peisa</a>. Here is the html:</p>
<p><code><br />
&lt;noscript data-large='Koala.jpg' data-small='Koala-small.jpg' data-alt='Koala'&gt;<br />
&lt;img src='Koala.jpg' alt='Koala' /&gt;<br />
&lt;/noscript&gt;<br />
</code></p>
<p>The values for the various sizes of image tags are stored in the data attributes on the noscript tag itself. Antti then provides sample jQuery code used to process the image:</p>
<p><code><br />
$('noscript[data-large][data-small]').each(function(){<br />
var src = screen.width &gt;= 500 ? $(this).data('large') : $(this).data('small');<br />
$('&lt;img src="' + src + '" alt="' + $(this).data('alt') + '" /&gt;').insertAfter($(this));<br />
});<br />
</code></p>
<p>These lines go through the document to find noscript tags with the appropriate data attributes. It tests for the screen size and then inserts a new img tag with the appropriate image path and alt tag.</p>
<h5>No race conditions!</h5>
<p>When using the noscript tag, there are no rendering race conditions. The image in the noscript tag never starts downloading. Mairead explained that “<a href="http://www.headlondon.com/our-thoughts/technology/posts/creating-responsive-images-using-the-noscript-tag">it works because children of the &lt;noscript&gt; tag are not added to the DOM</a>”.</p>
<p>This makes sense. The browser knows if javascript is available before it starts rendering a page. If javascript is available, there is no reason to worry about doing anything with items inside the noscript tag. If they aren’t getting added to the DOM, they certainly aren’t going to get downloaded.</p>
<p>This technique also has fallbacks if javascript isn’t enabled and doesn’t rely on cookies or htaccess files.</p>
<h5>Potential gotchas</h5>
<p>The biggest gotcha will be devices that profess to support javascript, but have poor implementations. For example, Blackberry 4.5 has javascript, but javascript cannot manipulate the DOM. Ergo, the noscript tag will not get used because scripts are available, but the script won’t successfully add a new img tag so no images will show.</p>
<p>Please note, this is speculation on my part. I know how Blackberry 4.5 behaves, but I haven’t tested this particular approach on a 4.5 device.</p>
<p>Even though this approach does not create a race condition, it is important that the javascript execute as quickly as possible. Inserting all of these images may require the browser to reflow the page. It also may cause the browser to load assets less efficiently because it cannot start prefetching assets.</p>
<p>Because of the need to execute as quickly as possible, it makes sense to remove the jQuery dependency from Antti’s javascript and put the code in the head of the document.</p>
<h5>Examples of this approach</h5>
<ul>
<li><a href="http://www.headlondon.com/our-thoughts/technology/posts/creating-responsive-images-using-the-noscript-tag">“Creating responsive images using the noscript tag</a></li>
<li><a href="http://www.monoliitti.com/images/">Testing Responsive Images</a></li>
<li><a href="https://gist.github.com/1200270">Responsive context aware images without cookies or server logic</a></li>
</ul>
<h4>Is screen size the right thing to look at?</h4>
<p>Most of these techniques rely on the size of the screen to determine what the image size should be. Andy Hume points out that the size of the screen may be misleading. He <a href="http://blog.andyhume.net/content-aware-responsive-images">writes</a>:</p>
<blockquote><p>The content driven approach to fixing this is to decide which image to load based on whether the image will be stretched beyond its true pixel width. If you stretch an image beyond its true width it begins to look pixelated or blurry. In this scenario, we want to load in a higher resolution version of the image.</p></blockquote>
<p><a href="https://github.com/ahume/Responsive-Images">Andy’s fork of the Responsive Images JS</a> tackles this problem (and adds support for nginx).</p>
<h3>Boston Globe Responsive IMGs are Busted</h3>
<p>I’ve been looking forward to the Boston Globe’s launch for quite some time. It is a tremendous feat of engineering and design. It has the volume of traffic necessary to test different approaches to responsive IMGs and see what works and what doesn’t.</p>
<p>The technique that they chose to use combines data attributes with cookies. Unfortunately, responsive IMGs are currently broken on the Boston Globe site. This is a known problem and they are working on fixing it.</p>
<p>The upshot is that we don’t yet have a large scale deployment of any of these techniques that we can interrogate and point to as validation that a particular combination is battle-hardened.</p>
<h3 id="mostpromising">Most promising javascript only techniques</h3>
<p>In my mind, cookies plus data-src and noscript are the two most promising techniques. Both have problems, but they have far fewer gotchas than other approaches.</p>
<h2>Server side solutions</h2>
<p>Most of the javascript techniques require little, if any, support from the server. There are alternate approaches that leverage the server for a bunch of the heavy lifting.</p>
<h3 id="uasniffing">User agent string parsing</h3>
<p>A few people have demonstrated solutions that do light-weight user agent string parsing to identify various mobile phones. If the user agent can be identified as iPhone or Android, then declare the device mobile and set the image size appropriately.</p>
<p>Unlike a lot of developers, I don’t have a problem with device detection based on user agent string. But if you’re going to start doing it for mobile, you have to take on real device detection via WURFL, Device Atlas, etc. Simplistic regular expression matching and assumptions about screen sizes isn’t going to work.</p>
<h3 id="devicedetection">Device detection</h3>
<p>There are a couple of different approaches that rely on device detection to determine the screen size and deliver an appropriate image back. Device detection databases are pretty good about having basic information like screen size.</p>
<h4 id="tinysrc">Sencha.io Src (formerly called TinySRC)</h4>
<p><a href="http://twitter.com/jamespearce">James Pearce</a> created a fantastic service called TinySRC. He later went to work for Sencha and TinySRC became Sencha.io Src. <a href="http://www.sencha.com/products/io/">Sencha.io Src</a> automatically resizes images for you. You reference Sencha.io Src in your img stag like this:</p>
<p><code>http://src.sencha.io/http://www.myapp.com/myimg.jpg<br />
</code></p>
<p>When a browser requests the url above, Sencha.io Src will look up the user agent of the device making the request to determine what size image is appropriate. It will then grab the image from your server and resize it. It then caches the resized image so that subsequent requests can be served quickly.</p>
<p>In addition to the automatic mode, Sencha.io Src will also allow you to specify specific sizes that you would like the image resized to.</p>
<h5>Combining Responsive Images JS with Sencha.io Src</h5>
<p><a href="http://twitter.com/#%21/andreatrasatti">Andrea Trasatti</a> forked Scott Jehl’s Responsive Images JS to <a href="http://blog.trasatti.it/2011/05/responsive-images-and-tinysrc.html">combine responsive IMGs with TinySRC</a>. The script finds the screen size using javascript and then uses htaccess to request the image at the correct size from Sencha.io Src.</p>
<p>Andrea’s version was written fairly early. It still uses dynamic base tags, url parameters, and results in “1 HTTP request for every image that we might avoid”. But all of these problems could be remedied by combining what Andrea started with some of the newer approaches.</p>
<h5>Potential drawbacks</h5>
<p>First, if you have a religious aversion to device detection, then you probably don’t want to use Sencha.io Src or you need to use it in a scenario where can specify the image size that you want.</p>
<p>As an aside, I’ve found it funny to see people who speak ill of device detection and user agent strings suggest that people use TinySRC. I once saw a slide deck that dismissed device detection and then a couple of slides later talked about how great TinySRC is. If only they knew.</p>
<p>On a more practical level, you have to evaluate whether or not the service will remain up and what happens if all of your content points to sencha urls that suddenly go away. I don’t think Sencha is going to go anywhere anytime soon. I know James well enough to know he’ll want to keep this service running forever if he can. But even all that said, looking at the long term availability of a service is something that needs to be considered.</p>
<h4 id="wurfl">WURFL-based solution</h4>
<p>WURFL is the largest open source device database. After attending the <a href="http://bdconf.com/">Breaking Development</a> conference earlier this month, Carson McDonald was inspired to develop a <a href="https://github.com/carsonmcdonald/ServerSideResponsiveImageExample#readme">WURFL-based solution for images</a>. It’s awesome to see something come together so quickly after the conference.</p>
<p>(BTW, <a href="http://bdconf.com/">Breaking Development</a> is the best conference in North America for web on mobile. Registration for the next event opens today. You should attend!)</p>
<p>Carson notes that his approach will likely have the same problems with CDNs and caching because different size images come from the same url.</p>
<h2>Image resizing services</h2>
<h3>Google’s mod_pagespeed</h3>
<p>Google’s <a href="http://code.google.com/speed/page-speed/docs/payload.html#ScaleImages">mod_pagespeed Apache module</a> automates many performance tasks and includes an option to scale any images on the fly. There are many ways to scale images (GD, ImageMagick, etc.). I decided to call out mod_pagespeed because it was one I hadn’t considered until I saw it suggested in a forum. I don’t know of anyone who has explored how it might be used in an responsive IMGs solutions.</p>
<h2>Combining client and server approaches</h2>
<h3 id="adaptiveimages">Adaptive Images</h3>
<p>As you can probably tell by now, there are few solutions that you can simply install and forgot about. Most require at minimum changes to the way you mark up the page. The two solutions that come closest to be plug and play are Sencha.io Src and <a href="http://adaptive-images.com/">Adaptive-Images.com</a>.</p>
<p>Adaptive images was developed by <a href="http://twitter.com/responsiveimg">Matt Wilcox</a>. It turns the premise of Responsive IMGs on its head by assuming that the markup on the page will contain the large versions of images and will not start with the mobile versions.</p>
<p>The solution consists of three pieces:</p>
<p>1. A small snippet of javascript placed in the head that sets a cookie with the screen width and height.</p>
<p><code>&lt;script&gt;document.cookie='resolution='+Math.max(screen.width,screen.height)+'; path=/';&lt;/script&gt;</code></p>
<p>2. A .htaccess that rewrites all requests for images to a php file. You declare directories that you want to exempt from this rewrite. For example, you don’t want your media query savvy CSS background images getting routed through the php file.</p>
<p>3. The php file which resizes the image based on breakpoints that you can configure.</p>
<p>The best part of Matt’s solution is that as long as you can separate out your image files so you can exclude ones that shouldn’t be resized, you can implement this technique without making any changes to your existing markup. Existing pages and posts will suddenly have different image sizes.</p>
<h5>And now for the problems</h5>
<p>Come on, by now you weren’t expecting it to be that simple did you?</p>
<p><span style="text-decoration: line-through;">Because the images start with the large size, if javascript is not available, the large size will be delivered. The most common devices to not have javascript support are older feature phones. The type of devices that will choke and even crash on large images are older feature phones.</span></p>
<p><span style="text-decoration: line-through;">This technique also suffers from the same race conditions that most of the javascript solutions do. The cookie has to be set early to avoid extra downloads.</span></p>
<p>Update: <a href="http://www.cloudfour.com/responsive-imgs-part-2/#comment-33653">Matt commented below</a> and points out that the default settings will result in a small image being delivered if javascript isn’t present. The markup will point to a large version, but the php file returns a small version. All of this is configurable.</p>
<p>Also, he is right that the result of the race condition <a href="http://www.cloudfour.com/responsive-imgs-part-2/#comment-33660">would not be multiple downloads</a>. I think the race condition still exists with different drawbacks, but I’m going continue the conversation in the comments where Matt and I can converse.</p>
<p>I also missed the fact that the url will stay the same regardless of the size of image which can cause issues with CDNs and proxy caching as noted earlier.</p>
<h3 id="yiibu">Yiibu profile approach</h3>
<p>Brian and Stephanie Rieger presented the work they did for <a href="http://browser.nokia.com/">browser.nokia.com</a> at Breaking Development conference. For that project, they invented a new way to combine client side information with device detection.</p>
<p>When a browser first requests something from the server, they don’t know anything about the device. So they check with a device detection database to see what they can find out about the size of the screen (and other details). They then check their own local database of tacit knowledge. This a database of things they’ve learned about how specific browsers work and any overrides they want to use. They use the combination of this information to deliver the appropriate HTML, javascript and images.</p>
<p>Once the browser gets this information, a javascript runs that tests the various aspects of the browser including screen size. It then stores this information in a profile cookie.</p>
<p>On the second request, the server receives the profile cookie and compares it to the information it has in its tacit database. It may update the tacit database. It combines the information into a revised profile combining server side information with client feature detection data.</p>
<p>I’m likely doing a poor job of describing the solution. Your best bet is to look at their slides:</p>
<ul>
<li><a href="http://www.slideshare.net/yiibu/adaptation-why-responsive-design-actually-begins-on-the-server">Adaptation: Why responsive design actually begins on the server</a></li>
<li><a href="http://www.slideshare.net/yiibu/pragmatic-responsive-design">Pragmatic Responsive Design</a></li>
</ul>
<p>This combined technique mitigates the problem of first load without any of the race conditions or potential problems that the client-only solutions have. It also extends beyond images to other content and javascript.</p>
<h5>Sounds great. What’s the catch?</h5>
<p>It is a complex system and requires significant changes to infrastructure to support. Bryan and Stephanie have published the approach, but the code isn’t available for download. It may be coming, but they took a well-deserved vacation after spending most of the summer working on the Nokia Browser project.</p>
<p>Probably the biggest problem with this approach is that most of us are not the Riegers. They have been doing mobile web for years. Their tacit knowledge of devices is exceptional. Freaking geniuses. That’s hard to replicate.</p>
<p>The same is true of the Boston Globe project. The team working on that included significant portions of the jQuery Mobile team and the <a href="http://twitter.com/beep">guy who coined the phrase responsive web design</a>. Few of us are going to be so lucky on our next project.</p>
<h2>Summary</h2>
<p>As I’ve reviewed the various techniques, I keep thinking back to something Andy Hume <a href="http://www.cloudfour.com/responsive-imgs/#comment-33388">said</a> in response to part 1:</p>
<blockquote><p>Our current solutions are hugely dependant on the current (and undefined) behaviour of browsers in regard to the page-load race conditions you mention. For example, most responsive image implementations would be compromised if a particular type of look-ahead pre-parser (<a href="http://goo.gl/TyzTi">http://goo.gl/TyzTi</a>) began to speculatively download images before actually parsing the HTML or executing any script. (<strong>I half expect us to get bitten by this any day.</strong>) One way or the other we need to consort with browser makers to get future-friendly.</p></blockquote>
<p>That’s the truth of it. Most of these techniques are based on our hope that browsers continue to download assets in the order we have observed to date. If the the order changes or if browsers start pre-parsing more aggressively, the whole house of cards may fall down.</p>
<p>In part 3 of this series, I’m going to look at the conversations going on about ways to change the img tag or replace it with something that will work better with multiple file sources.</p>
<h4>Sources and Acknowledgments</h4>
<p>I reviewed 18 different techniques for this post. My notes are captured in a <a href="https://docs.google.com/spreadsheet/ccc?key=0AisdYBkuKzZ9dHpzSmd6ZTdhbDdoN21YZ29WRVdlckE&amp;hl=en_US">Google spreadsheet</a> that you are welcome to review for detailed comments on each library. Thanks to everyone for publishing their thoughts and experiments. I learned a lot from each one.</p>
<p>This series wouldn’t have been possible without the assistance of <a href="http://twitter.com/scottjehl">Scott Jehl</a> and <a href="http://twitter.com/byranrieger">Bryan</a> and <a href="http://twitter.com/stephanierieger">Stephanie Rieger</a>. Scott in particular helped me sort out the problems with the main Responsive Images JS library. Thanks to all three of you for putting up with my many naive questions and for taking the time to explain all of the work you’ve been doing!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.kabayview.com/responsive-web-design/responsive-imgs-part-2-%e2%80%94-in-depth-look-at-techniques/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Responsive IMGs — Part 1</title>
		<link>http://www.kabayview.com/responsive-web-design/responsive-imgs-%e2%80%94-part-1</link>
		<comments>http://www.kabayview.com/responsive-web-design/responsive-imgs-%e2%80%94-part-1#comments</comments>
		<pubDate>Tue, 15 Nov 2011 14:28:04 +0000</pubDate>
		<dc:creator>Lynda Damiata</dc:creator>
				<category><![CDATA[Responsive Web Design]]></category>

		<guid isPermaLink="false">http://www.kabayview.com/?p=1053</guid>
		<description><![CDATA[September 27th, 2011 by Jason Grigsby &#124; cloudfour.com :: In my post “Where are the Mobile First Responsive Web Designs”, I noted that one of the first things I look for when trying to determine whether or not a responsive web design is “mobile first” is whether or not it has a strategy for handling <a href='http://www.kabayview.com/responsive-web-design/responsive-imgs-%e2%80%94-part-1'> [read more]</a>]]></description>
			<content:encoded><![CDATA[<p>September 27th, 2011 by Jason Grigsby |<br />
<a href="http://www.cloudfour.com/" target="_blank">cloudfour.com</a> ::</p>
<p>In my post “<a href="http://www.cloudfour.com/where-are-the-mobile-first-responsive-web-designs/" target="_blank">Where are the Mobile First Responsive Web Designs</a>”, I noted that one of the first things I look for when trying to determine whether or not a responsive web design is “mobile first” is whether or not it has a strategy for handling the IMG tag.</p>
<p>A recent Smashing Magazine <a href="http://www.smashingmagazine.com/2011/07/22/responsive-web-design-techniques-tools-and-design-strategies/">round up of responsive web design techniques</a> included several new approaches for handling IMG tags which makes it the perfect time to dig into this problem and the potential solutions in more depth.</p>
<h3>Why IMG Tags Suck for Responsive Web Design</h3>
<p>If you want your site to load as quickly as possible, you do want to deliver larger files than are needed. Many responsive web design sites provide mobile devices images at sizes appropriate for desktop and ask the mobile device to resize the image.</p>
<p>In my research, I found nearly <a href="http://www.cloudfour.com/css-media-query-for-mobile-is-fools-gold/">80% decrease in file size by delivering images at the actual size</a> they were going to be used on a mobile device.</p>
<p>So what’s the problem with the IMG element in responsive designs? Unlike CSS images which can provide different source files based on screen resolution using media queries, IMGs have a single source attribute.</p>
<h3>What are Responsive IMGs?</h3>
<p>Responsive IMGs are images delivered using the HTML IMG tag that come from different sources depending the screen size. There are many different techniques for accomplishing Responsive IMGs.</p>
<p>As far as I can tell, Scott Jehl first coined the phrase <a href="http://filamentgroup.com/lab/responsive_images_experimenting_with_context_aware_image_sizing/">Responsive Images</a> to describe a javascript solution to the img source problem. He also referred to Responsive IMGs as a general term <a href="http://twitter.com/#%21/scottjehl/status/95505111572418561">recently</a> so I’m hopeful he doesn’t mind the fact that I’m extending his definition to describe any technique that attempts to provide images at an appropriate size for a responsive design.</p>
<h3 id="challenges">Responsive IMGs Challenges</h3>
<p>There are some common challenges that any Responsive IMG technique will face. As we review the various techniques that have been proposed, we need to keep these challenges in mind.</p>
<h4>Minimum Bar: Start with Mobile, No Extra Downloads</h4>
<p>Scott Jehl set a <a href="http://twitter.com/#%21/scottjehl/status/95505111572418561">minimum bar for Responsive IMGs</a> by stating they must do the following:</p>
<ol>
<li>Start with mobile img</li>
<li>Upgrade to larger size without downloading both</li>
</ol>
<p>Both of these are worthy and necessary goals.</p>
<h4 id="firstload">The First Page Load Problem</h4>
<p>Any solution that relies on client-side scripting to make a decision about what image source to display will suffer from a first page load problem. The first time someone visits a site, the server won’t know what size image to provide.</p>
<p><img class="aligncenter size-full wp-image-1054" title="unknown-vessel" src="http://www.kabayview.com/wp-content/uploads/2011/11/unknown-vessel.jpg" alt="responsive images 1" width="500" height="375" /></p>
<p>Image from Bryan Rieger’s <a href="http://www.slideshare.net/yiibu/muddling-through-the-mobile-web">Muddling Through the Mobile Web</a> presentation, photo by <a href="http://www.flickr.com/photos/wscullin/3770015203">wscullin</a>, licensed under <a href="http://creativecommons.org/licenses/by/2.0/">Creative Commons</a>.</p>
<p>If javascript is added that determines what image size is appropriate, then this information can be retained for the user session via cookies or similar techniques. In theory, on subsequent requests the server can make a decision about what size image to include in IMG tag.</p>
<p>FWIW, the speed of first load is a big deal. The speed of a person’s first experience can dictate their impression of a product and company. Google, Yahoo and others have talked about how minor speed differences makes a big difference in usage of their products.</p>
<h4 id="raceconditions">Rendering Race Conditions</h4>
<p>Techniques that rely on adjusting the image source attribute via javascript need to make sure that the modification happens before the image requests start.</p>
<p>Browser makers have done a lot of work to download as many assets as possible at the same time. Usually this is a good thing. But in the case of responsive imgs, the javascript needs to evaluate what size image to retrieve before any image requests start.</p>
<p>A lot of earlier work was done using dynamic base tags. This worked when the javascript was inline in the head tag, but failed to prevent images from downloading twice when an external javascript file is used.</p>
<p>The upshot is that nearly every client side technique requires deep understanding of the order in which different browsers process and download assets. Or more realistically, each approach needs to be tested extensively.</p>
<h4 id="cdn_caching">Content Delivery Networks and Caching</h4>
<p>When you deliver different size images at the same url, you can run into problems with CDNs and other caching at the edge of the network. If the first person to request an image is on a mobile phone, people who follow via the same CDN or cache will also see the mobile-optimized image even if they are on desktop unless consider CDNs in your strategy.</p>
<h3 id="futurefriendly">Future Friendly Responsive IMGs</h3>
<p>If we accept that the “quantity and diversity of connected devices—many of which we haven’t imagined yet—will explode”, then we need to consider look for solutions that are <a href="http://futurefriend.ly/">future friendly</a>. In addition to the current experimentation, we need to start thinking about what a long term solution might look like.</p>
<p>For example, many of the early solutions for Responsive IMGs consist of two size images: one for desktop and one for mobile screen sizes. Will two image sizes really suffice for all of the devices that are coming?</p>
<p>Also, a lot of the solutions right now tackle one part of the problem. They may tackle the client side changes to switch the image source, but leave as an exercise for the developer to figure out how image resizing will be handled. For shared libraries, limited scope makes sense.</p>
<p>But as we look at what systems will need to do to be successful in the future, we need to think about what we want out of both the server and client side.</p>
<p>Here are some of the things that I think a future friendly technique will need to consider:</p>
<ul>
<li id="arbitrarysize"><strong>Support arbitrary image resizing</strong> — We cannot anticipate what screen sizes may be coming. We need systems that handle image resizing automatically and support any arbitrary size needed for a particular page.</li>
<li id="artdirection"><strong>Art direction can override automatic resizing</strong> — Not every image can be resized without losing the meaning of the image. Sometimes cropping an image may work better than resizing it. Automatic tools need to easily support manual override.</li>
</ul>
<p><img class="aligncenter size-full wp-image-1055" title="unreadable-image" src="http://www.kabayview.com/wp-content/uploads/2011/11/unreadable-image.png" alt="unreadable image" width="500" height="375" /></p>
<ul>
<li id="highres"><strong>Support for higher resolution displays</strong> — What do we do with the iPhone 4’s <a href="http://www.apple.com/iphone/features/retina-display.html">retina display</a>and other devices sharing similar high resolution screens? It is an open question about whether we should deliver higher resolution images to those devices given the performance hit that will occur if the person is on a slow connection.But regardless of how we chose to handle it right now, it is clear that the trend towards more pixels per inch on displays is not going away. If anything, we’re seeing indicators that higher density will soon be available on desktop displays as well.This means that our current definition of what is a large image for web is probably too small for future devices. With that in mind, it probably makes sense for systems to accept the highest resolution image possible—even if that resolution isn’t currently being used—so that when new devices become available the high resolution source is already available and hasn’t been lost.</li>
<li id="speed"><strong>Connection speed should be part of the criteria</strong> — We can be much smarter about the size of the image we deliver if we can tell something about the network connection. We need an easier way to get at this information.</li>
<li id="new-img-tag"><strong>A replacement for the IMG tag?</strong> — All of the responsive image solutions are attempting to deal with the fact that the image tag has only a single source. There have been various proposals recently to take a new look at what the tag should be and see if we can find a long term replacement.</li>
</ul>
<p>That’s my short list. <strong>What would you add?</strong></p>
<p>In part 2, I’ll take a closer look at the current alternatives for responsive imgs and which ones hold the most promise.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.kabayview.com/responsive-web-design/responsive-imgs-%e2%80%94-part-1/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

