HTML/CSS

The Place for Styles in HTML and XAML

I got a question from the community.

When working on a Windows app, how do you get a complete list of the style properties that apply to any given HTML element?

The short answer is you don’t. And that’s not a Windows thing, it’s an HTML/CSS thing.

With a language like XAML/C#, you have properties that apply to certain elements because of the way everything works behind the scenes. It’s all strong typed and inherited, so when you start typing the name of a property, Visual Studio is able to look into the typing system and see which properties apply and suggest them via Intellisense. But with HTML/CSS, the CSS properties don’t belong to certain elements. Instead any property can be applied to any element and it’s up to the browser (hopefully adhering to the standards) to implement what happens. Some are obviously ignored. It doesn’t make any sense, for instance, to set the font of an image, so the image element will simply ignore it. This is not really a big problem in my experience. You come to realize which properties have which effect on which element at the same time that you learn what the properties are and what they do. And they’re mostly intuitive. But we can thank the openness and democratic nature of HTML/CSS for the matter.

The best way to get a complete list of CSS in my opinion is to bookmark aka.ms/iedevcenter and then visit that and click on CSS under the Develop section.

And the second part of the question was…

Why is it never a good idea to inline style properties when using HTML/CSS. After all, in XAML, we often write the properties right there in the declaration of each element.

The fact is that in both HTML and XAML, you can choose to add your styles inline (that is, within the element in the HTML page), or at the page level (in a

Microsoft's Vendor Specific CSS Prefixes

Much of my audience, I’ll presume, has at least some familiarity with CSS.

If you have none, then let me simply say that CSS is basically a big, flat list of style and layout properties that are grouped together into rules and determined to affect certain portions of an HTML document.

I like to draw the analogy to the classic word processor, because pretty much everyone has experience with a word processor. When you’re working on a letter to grandma and you want to emphasize that you don’t like nuts in your brownies, you might choose to bold that text, right? So you first select the important words and then you affect them with a bold command.

CSS works like that. You write selectors that identify certain parts of your UI and then you define properties and values that affect them.

Most of the available CSS properties are governed by a standards body - the W3C. They are a consortium of companies with a vested interest in web technologies that put their heads together and decide on the best way to do things. They decide things like “hey, let’s do away with the tag and use a tag instead because it’s more semantic”. All of the other smart guys in the room say “good idea!” and then they spend 18 months going through the paperwork to make the standard final. That’s a bit of exaggeration laced with cynicism perhaps, but it is frustrating sometimes that the W3C can’t turn the ship quicker. It’s a big ship. I’ll give them that.

Once you’ve selected your target HTML elements with a well formed CSS selector, you go about choosing properties, and in Visual Studio that leaves you somewhere like this…

…that is, Intellisense gives you an enormous list of CSS properties. All of them. And it pretty much has to. There’s not really a way for the tooling to know which properties you might apply. More strongly typed UI frameworks define which properties can be applied to which UI elements, but in the world of HTML and CSS, you can apply anything to anything. It may not do anything or it may do something different, but you’re free to do it.

If you scroll to the top of that Intellisense list, you see this…

…that is, a bunch of properties that are prefixed with -ms-. That means that these are Microsoft specific properties. We actually call them vendor specific and the syntax (a dash, a vendor code, and another dash) is part of the standard, and it’s a good one in my opinion. It means that vendors will forever be free to do custom stuff and it will be readily apparent to everyone that it’s not necessarily part of the standard.

When you see a vendor specific prefix it means one of three things:

  • the property is simply a feature or extension of a Microsoft product (usually Internet Explorer) and is not defined in the standard
  • the property is part of a CSS spec that has not been run through all of its paperwork yet
  • the property is part of a CSS spec that is final, but the feature is only partially implemented so far

I found it helpful to look through the many Microsoft vendor specific properties and see what they do. It gave me an idea of where IE is relative to the standards (it’s doing pretty good these days by the way) and also an idea of what I can do when I’m targeting an IE browser only (such as when I’m building a Windows app using JavaScript). I’d like to enumerate them for you, because they aren’t necessarily easy to find. My first search brought properties compatible with Windows Mobile 6.5. Oops!

Here’s the complete list as of today with links to documentation. Do keep in mind that the list is rather time-sensitive and very subject to change. Also, know that some of these are not required for later versions of Internet Explorer, but are still supported for backward compatibility.

  • -ms-accelerator
  • -ms-behavior
  • -ms-block-progression
  • -ms-content-zoom-chaining
  • -ms-content-zooming
  • -ms-content-zoom-limit
  • -ms-content-zoom-limit-max
  • -ms-content-zoom-limit-min
  • -ms-content-zoom-snap
  • -ms-content-zoom-snap-points
  • -ms-content-zoom-snap-type
  • -ms-content-zooming
  • -ms-filter
  • -ms-flow-from
  • -ms-flow-into
  • -ms-grid-column
  • -ms-grid-column-align
  • -ms-grid-columns
  • -ms-grid-column-span
  • -ms-grid-layer
  • -ms-grid-row
  • -ms-grid-row-align
  • -ms-grid-rows
  • -ms-grid-row-span
  • -ms-high-contrast-adjust
  • -ms-hyphenate-limit-chars
  • -ms-hyphenate-limit-lines
  • -ms-hyphenate-limit-zone
  • -ms-hyphens
  • -ms-ime-mode
  • -ms-interpolation-mode
  • -ms-layout-grid
  • -ms-layout-grid-char
  • -ms-layout-grid-line
  • -ms-layout-grid-mode
  • -ms-layout-grid-type
  • -ms-line-break
  • -ms-overflow-style
  • -ms-perspective
  • -ms-perspective-origin
  • -ms-perspective-origin-x
  • -ms-perspective-origin-y
  • -ms-progress-appearance
  • -ms-scrollbar-3dlight-color
  • -ms-scrollbar-arrow-color
  • -ms-scrollbar-base-color
  • -ms-scrollbar-darkshadow-color
  • -ms-scrollbar-face-color
  • -ms-scrollbar-highlight-color
  • -ms-scrollbar-shadow-color
  • -ms-scrollbar-track-color
  • -ms-scroll-chaining
  • -ms-scroll-limit
  • -ms-scroll-limit-x-max
  • -ms-scroll-limit-x-min
  • -ms-scroll-limit-y-max
  • -ms-scroll-limit-y-min
  • -ms-scroll-rails
  • -ms-scroll-snap-points-x
  • -ms-scroll-snap-points-y
  • -ms-scroll-snap-type
  • -ms-scroll-snap-x
  • -ms-scroll-snap-y
  • -ms-scroll-translation
  • -ms-text-align-last
  • -ms-text-autospace
  • -ms-text-justify
  • -ms-text-kashida-space
  • -ms-text-overflow
  • -ms-text-size-adjust
  • -ms-text-underline-position
  • -ms-touch-action
  • -ms-touch-select
  • -ms-transform
  • -ms-transform-origin
  • -ms-transform-origin-x
  • -ms-transform-origin-y
  • -ms-transform-origin-z
  • -ms-user-select
  • -ms-word-break
  • -ms-word-wrap
  • -ms-wrap-flow
  • -ms-wrap-margin
  • -ms-wrap-through
  • -ms-writing-mode
  • -ms-zoom
  • -ms-zoom-animation

The Semantics of HTML and XAML

I had a question from a developer in my community and I decided to respond via a blog post.

I have taken liberty to distill and rephrase the question as follows…

HTML is less verbose than XAML, but it’s often times harder to figure out what’s going on with a bunch of div’s on the page. How do you determine by looking at your HTML what’s going on with the styling? Shouldn’t it be more like XAML - easy to read?

What we’re talking about here fundamentally is called semantics.

Let’s dig in.

Readable UI Code

We’re developers. We write code for a living. The designers of the coding languages we use have to strike a fine balance. The code has to be read by computers and humans, and I’m not sure if you’re aware, but the two are more different than they are alike.

These days, compiler technology has advanced to the point where we’re able to make almost any code understandable by computer, so we’re left with the bigger challenge - the human.

A developer should not just be able to read and write the code. He should enjoy it. He should feel as though, even if the language hardly resembles his spoken language, that it is still an expression and extension of his thoughts and the implementation of his logic.

Occasionally, we write user interface code and we target eye balls. With UI, the attempt to is show something that a user can quickly understand and interact with. Its importance can hardly be overstated. Actually, in light of world affairs, I can’t exactly call it critical, but in determining the degree to which users enjoy a platform or enjoy using your app, it certainly is.

Other times, the code we write simply targets results. That web service operation comes back with an answer. That’s all. As long as it comes up with the right answer, we couldn’t care less how it does it.

In this article, I’m going to focus on UI code.

HTML

The UI language of the web is HTML. It has been for a couple of decades. Talk about ubiquity! Pretty much every device in existence has the ready capability of interpreting HTML (most often, obviously, it’s the browser).

For apps, there’s not nearly so much ubiquity. The UI language of most devices is proprietary. Generally, they’re more powerful than earlier versions of HTML, but pretty much on par with HTML5.

XAML

Such is the case with XAML. XAML is the UI language of Windows platforms.

XAML looks somewhat like HTML with all kinds of anglies (<>) everywhere, and the analogy is a direct one. In both cases, what we’re trying to accomplish is to instantiate (or declare) an interface. We’re not trying to implement any business logic.

Two Reasons for the Readability

As I see it, there are two main reasons that XAML tends to be easier to read. The first is the language itself. The second is the tendency for developers to conjoin element instantiation with layout and styling. Let’s discuss both of these…

XAML is More Semantic

As I mentioned earlier, HTML is over 20 years old, while XAML is less than 10. Plus, HTML has evolved with the help of a vast community of individuals and organizations, while XAML has been directed by a single organization with input from developers.

Consequently, HTML has been a semantic disaster. The UI elements defined by HTML have evolved along with the overall function of HTML. HTML was originally designed to mark up documents and give them some presentation meaning - think bold text, block quotes, borders, etc. HTML is presently chartered with providing full-fledged application UI capabilities.

So, in HTML, you have often seen the same element (the div) used for many nested levels of generic containers.

Recently, HTML5 has added tags to improve its semantics, but few of them actually indicate the layout or style of elements in the document.

Separation of Instantiation and Styling

An now for the second major reason that that XAML tends to be easier to read than HTML.

When we define UI, we’re doing two things essentially - we’re creating UI elements and then we’re laying them out and styling them.

In HTML, the role of instantiating elements is usually separate from the role of laying them out and styling them. The HTML does the instantiating and the CSS does the layout and style.

A typical XAML document, on the other hand includes both roles. It’s certainly possible and usually recommend as good practice to separate styles, but more often they are all done in the same file.

An Example

Look at the HTML and XAML in the following simple example. Both do approximately the same thing. They render 3 boxes side by side across the page next to one another.











HTML



XAML





  <div></div>

  <div></div>

</div>

</td>
<td>












        </td>
    </tr>
</tbody>


In this example, it’s easy to see the difference between the languages.

The HTML is using a div with div’s, and a div does not elude to its graphical intent. In other words, it does not convey layout, but only structure and containment.

From the HTML, we can tell that we have a container that has three child containers, and that’s all we can tell.

The XAML, on the other hand, conveys quite a bit of layout as well as structure. In it, we can tell that we’re going to have a horizontal arrangement of size 100 boxes.

As I mentioned already, a person can pull the styling out of a XAML document to create a separation. Likewise, one can add the styling in to an HTML file. It’s not as easy or elegant with XAML to create a divide, and it’s not as easy or elegant with HTML to join them. It’s a difference in the nature of the languages.

Implications

We’ve established something about the difference in nature between HTML and XAML, so where does that leave us?

I think that leaves us with two impressive UI languages that are each suited to assist with different scenarios and different developer preferences.

HTML is better at…

  • creating a UI that works just about anywhere
  • creating a responsive UI that adapts to various display conditions
  • providing concise, generic UI syntax that can adapt and specifies no display characteristics explicitly

XAML is better at…

  • bringing the next developer to look at your code up to speed quickly
  • solid, pixel perfect, and predictable control over layout
  • practically unlimited possibilities for importing custom doohickies, gadgets, and thingies

Conclusion

So, is XAML more semantic than HTML? Yes.

Why? Because that’s the way it’s been designed and the way it’s evolved.

Is it possible to express HTML as semantically as XAML? Not quite. It’s possible to embed styling into HTML and make it more verbose, but it is fundamentally less semantic.

Are HTML’s semantic deficiencies a bad thing? Maybe. XAML fans certainly get a lot of enjoyment ridiculing it, but it has its advantages - mainly in its ability to separate style and maintain a generic document structure.

Hope that helps. Thanks for listening.

Easy Caching in WinJS Apps

I set out the other day to help a developer add some cache functionality for his app.

The app is 1Vigor and there’s a version for swimmers, one for runners, and another for learning how to generate peak performance in whatever sport or fitness activity you’re doing (not quite ready for the Store). The 1Vigor apps pull content from the 1vigor.com website and provide some great articles for athletes. The authors of the articles are first rate and the amount of content available is impressive too.

The swimming and running apps are already in the store, but if you download them, you’ll discover that you’ll be required to maintain an internet connection while you fetch your next article to read, since no cache functionality exists. So if you’re on a submarine without wifi, you’re going to be out of luck. I’m not completely sure, but I don’t think that wifi availability on submarines is quite caught up with commercial airlines.

My first thought was that I was going to have to take a very manual approach to caching. I was prepared to enumerate each article and save a copy in local storage or something like that. As it turned out, it was a much easier task.

Here’s the only code required to accomplish the task at hand…

var results = WebData.articles.map(function (a) {
return WinJS.xhr({ url: a.contentUrl });
});
WebData.articlesCached = WinJS.Promise.join(results);

And here’s what that does. It starts with the WebData.articles - an array containing objects with the metadata about the articles and including a URL (contentUrl) linking to the HTML of the article from 1vigor.com.

It maps that array to a WinJS.xhr call. If you’re not familiar with the .map() function, listen up. The .map() function works for all arrays (because it exists in the prototype for the Array object). When you map an array, you are changing all of its elements to something else.

Let’s say you have an array (A) of numbers and you want to create a new array (B) where all of the numbers from A are doubled. You could do that with…

var B = A.map(function(i) { return i*2; });

So, back to the first block of code… the value of the results variable is going to be an array of Promise objects.

You can wait for all of the promises in an array to complete by using WinJS.Promise.join(myArrayOfPromises).

So the articlesCached variable which I hang on the WebData object is going to be a promise that completes when all of the individual calls to the article content are complete.

Now, you might be wondering at this point what I do with the results of those HTTP requests. The answer is that I do nothing with them. I don’t need to. GET requests over HTTP are cached by default, so the next time the user launches an article and the system attempts to access its content using the .contentUrl, it essentially says “Hey, I’ve done this before. I’ll just use the results of that last network call instead of doing another one.”

And that’s all it took.

Not bad, eh?

The Flexbox CSS Standard

Question: what is Microsoft’s position on Flexbox and fallbacks for IE10 and legacy?

While I’m not the official voice of Microsoft and am not the smartest Softie in Redmond when it comes to the web standards, I’ll attempt to answer this question anyway.

The official standard for the flexbox style in CSS is documented in exhaustive detail at W3C. The abstract of this implement is helpful stating that the flexbox is

“…a CSS box model optimized for user interface design. In the flex layout model, the children of a flex container can be laid out in any direction, and can “flex” their sizes, either growing to fill unused space or shrinking to avoid overflowing the parent. Both horizontal and vertical alignment of the children can be easily manipulated. Nesting of these boxes (horizontal inside vertical, or vertical inside horizontal) can be used to build layouts in two dimensions.”

I think the official answer is that Microsoft doesn’t have an official position on falling back from flexbox. The -ms-flexbox is an implementation by the Trident engine to the flexbox… end of story. You will, however, find some recommended strategies on the web, and the best I’ve run into so far is the use of inline-block for unsupporting browsers.

That said, I’m spending most of my time with Windows 8 apps these days am thus spared the pain (the ever building pain that has yet to reach a crescendo) of writing 12 lines of code to accommodate the various HTML/CSS engines. If I was doing web development for the masses, I think I would decide to avoid the use of flexboxes altogether to ease my pain. I’m not sure what’s worse - an old, hacky solution or multiple solutions to maintain (one of which is still old and hacky).

Box Sizing

Don’t miss the box-sizing property in CSS. It’s important. I’ll tell you why.

Let me start by showing you a diagram of the HTML box model.

Let’s talk about a div, for example. If you create a div and then use CSS to assign some margin, a border, and some padding as well as the content that you include within the div element, you would end up with something that looks like the image above. Most people with some HTML and CSS experience are very familiar with this.

When you set the size (width or height) of that div using CSS, the size values that you specify apply in an… um… interesting way. The size values apply to the content area. That’s a little bizarre, because in real life (the one we’re all familiar with) when we talk about the size of a box of stuff, we are talking about the size of the outside of the box.

This is a problem because if you want to set an element to the width of the screen and you use width:100%, even that 100% does not include the padding, border, and margin, so if you have any of those then your box will run off the edge of the screen.

You can change this behavior though with a simple CSS property. If you set box-sizing to border-box (instead of the default content-box), then the same value of 100% for your div’s width will now include the border and padding. It will still not include the margin, by the way.

Hope that helps.

Query Your DOM

Your HTML describes the structure and sequence of your document. It’s the starting point for your UI. But it’s just the starting point. Things change. Items get added, removed, or moved. Styles change. Dialogs appear and disappear, and the user touches things and drags them around. All (or at least most) of this interaction happens in JavaScript where you can instruct your document in the language of code to react to your user and do what you command.

Before you can move something, remove something, or add to something, though, you’ll need to select it. That’s what I’m going to talk about here. I’m going to talk about selecting one or more elements from your document object model (DOM) from JavaScript so you can work with them. This is called querying the DOM.

It used to be rather difficult to query the DOM. When I was a kid I not only had to walk uphill to school both ways, but I also had to use rudimentary and often proprietary JavaScript functions for getting access to in my HTML. The popular getElementById() was helpful but it only ever got one thing at a time. Usually, I resorted to looping through document.all() and asking questions about each and every element on the page to see if it was in my reticle for the change I had in mind.

Today, things are different. When I first met jQuery and started selecting from the DOM using the CSS selector syntax I already knew, it was love at first $. When I started Windows 8 development using HTML/JS I remember thinking “okay… but only if I get to take jQuery in with me”. But since I’ve hardly used it. The reason is that ECMAScript 5 introduced querySelector() and querySelectorAll(). These yumful functions take CSS queries just like the jQuery selector syntax and return (respectively) a single DOM element or a list of nodes.

Besides these selection methods, WinJS also added a couple of functions (that just wrap querySelector and querySelectorAll BTW). They are id() and query() and they’re in the WinJS.Utilities namespace.

I talk all about of these selection methods in a previous post called Selecting Elements in a Windows 8 HTML App.

I liked using querySelector and querySelectorAll because they were the closest to the metal being right in the JavaScript language, but there was one thing I didn’t like about them. querySelector returns a DOM element… that’s fine. querySelectorAll returns a node list, though and I usually want to work with an array so I can use all of the ECMAScript 5 array functions. So I wrote a wrapper that I simply call q() which stands for query. It’s short and has a little bit of abstract functionality that I like, and I wrote a post about it too. It’s called Query Selector Helper for Metro Apps. But I have since upgraded the helper function to allow the caller to force the result of the call to be an array. That way, even if it is only a single result that is returned, it will return it as an array of one, so the caller doesn’t have to have switching logic.

I keep the latest version of this function in my ocho.js library which is part of my codeSHOW project on CodePlex. So to get the latest version of the helper, simply go to http://codeshow.codeplex.com, go to the Source Code tab, choose Browse, and then browse to /codeSHOW/js/ocho.js.

Enjoy!

msMatchMedia - programmatic access to media queries

If you throw down with a media query like this…

@media screen and (-ms-view-state: fullscreen-portrait) {
p { color: purple; }
}

…then you’re going to get purple text in all of your paragraphs, right?

Well, what if you wanted to check to see if you were in fullscreen-portrait from your code so you could do something fancy. Of course, you get some help from Windows with that. If you’re using the navigation project template then you can implement an updateLayout method when you define a page and one of the parameters you’ll receive is viewState.

But you might not be in the updateLayout method and you might want to check some other media query property such as whether the screen is at least 600px wide.

That’s where you may benefit from accessing media queries programmatically.

To execute the media query above from could you can do this…

if (msMatchMedia("(-ms-view-state: fullscreen-portrait)").matches) {
//do something if we're in portrait
}

This msMatchMedia method hangs off of the window object.

I know that there are usually properties in the DOM API that will allow you to discover these things about your environment, but if media queries are your thing and you can solve the issue that way, then there you go.

CSS Tip: nth-child and nth-of-type Pseudoclasses

Let’s say we have the following HTML…

<ul class="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>

That’s not difficult. It’s a ul (unordered list) which is by default rendered with bullets, although you’ve got full control over how exactly you want it to render. In this case, we have 6 items. Simple. And here’s how it should render in an empty Windows 8 app (with the default dark theme)…

Now what if we wanted every item to be yellow? Go ahead and think about how you’d do it before you look at my answer.

Here it is…

.list li {
color: yellow;
}

That’s easy enough. Now what if we wanted to give every other item a dark blue background? Well, there are at least four ways I can think of to do that. I’ll include all four.

The following two are equivalent and will highlight every other line starting with the first…

.list li:nth-child(2n-1) {
color: yellow;
}
.list li:nth-child(odd) {
color: yellow;
}

The first rule contains a formula and the second simply contains the word odd. This nth-child is called a pseudo-class because we didn’t have to manually decorate every other li tag with a class in order to select them. Instead, we use a pseudo-class. Much easier.

The nth-child pseudo-class uses a formula that is always of the form: an+b. Essentially, CSS is going to plug a set of positive integers starting with 0 into the n in that equation. The result will be a set of integers. CSS will omit the negative and zero values and use the resulting positive integers to determine which items should be matches.

Our 2n-1 formula then would evaluate to an integer set that looked like [-1,1,3,5,7,9,…]. CSS would then ignore the -1 and apply this style to the 1st, 3rd, and 5th elements. Because highlighting every other row is likely a very common case, CSS defines the odd keyword to simplify matters.

The following two are also equivalent and will highlight every other line starting with the second…

.list li:nth-child(2n) {
color: yellow;
}
.list li:nth-child(even) {
color: yellow;
}

Again, the first is an equation and the second is a keyword. The set of positive integers [0,1,2,3,4,5,…] would get evaluated in that equation to [0,2,4,6,8,10,…]. The 0 would be ignored, and the 2nd, 4th, and 6th list items would have the style applied. Here’s the result…

Here are some other, more advanced uses of the nth-child pseudo-class…

Formula Result
3n Every 3rd element
10n Every 10th element
-n+7 The first 7 elements
n All elements (pointless)
n+4 All elements starting with the 4th
2n+3 Every other element starting with the 3rd

And if you want to see some more, go to Useful :nth-child Recipes on [CSS Tricks](http://css-tricks.com.

So there you have it. That’s nth-child. Pretty handy, eh?

Now let’s look at nth-of-type and see how it differs from nth-child. Consider the following HTML now…

<div class="list">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<div>Child Div 1</div>
<div>Child Div 2</div>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
<p>Paragraph 5</p>
<p>Paragraph 6</p>
</div>

Now we have a div that has mixed child types. It has some p elements and some child div elements.

When we attempt to apply the same blue style to the second div using our nth-child syntax…

.list div:nth-child(2) {
color: yellow;
}

We don’t get the desired effect. Nothing will be highlighted. See, the nth-child pseudo-class is indicating that our target element has to be the 2nd child, but it’s not. It’s the second div, but it’s not the second child. To specify that we’re looking for the second div, we use nth-of-type like this…

.list div:nth-of-type(2) {
color: yellow;
}

And that brings us to the end of the post. If you have any questions or comments, please feel free to leave them below.

When to Use ViewBoxes and FlexBoxes

HTML and CSS is great, but there’s at least one thing that has driven web designers mad for ages - layout. We used to use tables and it worked. We knew their weaknesses, but they worked. Then we were told that tables are for tabular data and div elements are for layout, but divs are wretched creatures. To set divs next to each other one had to float them, but then when finished floating had to be explicitly turned off - argh. Also, divs had no notion of filling vertical space or of controlling the vertical placement of anything within it.

So a myriad of web designers resorted to absolute positioning, browser hacks, jQuery UI positioning, or some other means just to get things to go where they ought.

Enter Windows 8.

Windows 8 allows us to design our Metro style apps using HTML and CSS. In doing so, however, it the CSS standards and Microsoft have given us some facilities to finally place things where we want them.

It’s not obvious how everything works though so let me give you a boost. If you start with a Fixed Layout Application (for the record, I think it should be called the Flexible Layout Application) project template you get the right stuff automatically, but here’s an explanation so you have the concept as well.

We’re dealing with two entities here: the WinJS.UI.ViewBox control and the -ms-flexbox css property value (for the display property).

WinJS.UI.ViewBox

The purpose of the ViewBox is stated in the documentation. It says that it “Scales a single child element to fill the available space without resizing it. This control reacts to changes in the size of the container as well as changes in size of the child element. For example, a media query may result in a change in aspect ratio.”

The first thing I had a hard time wrapping my head around was the overlap between a ViewBox and a FlexBox. Then I discovered that there really isn’t any. The ViewBox control is quite simple. It scales the content that it contains but maintains it’s aspect ratio.

It works like this…

Note that it does not work like this…

In other words, as it says in the documentation, it scales the contents, but it keeps their proportions.

And that’s really the end of it. The ViewBox serves this one purpose.

Flexbox

Now it’s time to talk about the flexbox. This is not a WinJS control, but rather an implementation of a CSS3 property. It’s not quite a standard property yet because all of the browsers are still implementing it with vendor specific properties and values, but it’s close. For Windows 8, we specify a display property with a value of -ms-flexbox to indicate flexbox layout.

The purpose and scope of the flexbox is a bit bigger than the ViewBox. Here’s what the W3C spec for the CSS Flexible Box Layout Module says “In the flexbox layout model, the children of a flexbox can be laid out in any direction, and can “flex” their sizes, either growing to fill unused space or shrinking to avoid overflowing the parent. Both horizontal and vertical alignment of the children can be easily manipulated. Nesting of these boxes (horizontal inside vertical, or vertical inside horizontal) can be used to build layouts in two dimensions.”

So, like the ViewBox, we still have the concept of the container’s content changing in size to fit the container, but this has more to do with a collection of child items.

Additionally, the flexbox offers a lot of properties to specify how it’s children are laid out. A quick glance in Blend at the CSS properties on a div in the Flexbox category will enumerate them for you…

Notice first the -ms vendor specific prefix as I mentioned.

To give a thorough description of the possibilities with these properties, I’d be duplicating what’s already done quite nicely on the flexbox page on w3.org, so just go there and read the nitty, gritty detail.

Differences

The ViewBox is a WinJS control, whereas the flexbox is a CSS property.

The ViewBox always acts on a single child item, but the flexbox can act on multiple child items.

The ViewBox itself changes size to fit it’s container as a core feature. The flexbox can be told to scale to 100% either in width or height, but it doesn’t have to.

The ViewBox does not extend control over the alignment and scale modes of it’s contents, but always does the same thing - scales the child item without changing it’s proportion.

All Together Now

Now that you know how different these controls are, consider them together. If you put a flexbox div inside of a ViewBox, you get a really effective layout tool. Try this for your HTML…

<body>
<div data-win-control="WinJS.UI.ViewBox">
<div class="flexy">
<div class="item">A</div>
<div class="item">B</div>
<div class="item">C</div>
</div>
</div>
</body>

With this as the CSS…

.flexy {
-ms-flex-align: center;
-ms-flex-direction: column;
-ms-flex-pack: center;
display: -ms-flexbox;
}
.item {
height: 200px;
width: 200px;
border:solid 1px;
font-size:9em;
}

What you have now is a flexbox that fills its area well. Look at these simulator screenshots so you can see what this would look like…

[more images missing]

XAML is unarguably the most powerful layout engine I’ve ever seen, but I really don’t feel like there’s too much in HTML/CSS that we’re missing now with additions like this. It’s rather empowering.

Happy layouts!