If you use the shorthand, any longhand background propertyvalue that’s omitted from the declaration will default to the longhand property’sdefault or initial value.. The default values f
Trang 1The background images are layered one on top of the other with the first declaration
on top, as if it had a highz-index The final image is drawn under all the imagespreceding it in the declaration, as if it had a lowz-index Basically, think of theimages as being stacked in reverse order: first on top, last on the bottom
If you want to declare a background color—which you should, especially if it’slight-colored text on a dark-colored background image—declare it last It’s oftensimpler and more readable to declare it separately using thebackground-colorproperty
As a reminder, the shorthandbackgroundproperty is short for eight longhandbackground properties If you use the shorthand, any longhand background propertyvalue that’s omitted from the declaration will default to the longhand property’sdefault (or initial) value The default values for the various background propertiesare listed below:
Just like for a declaration of a single background image, you can include a gradient
as one of several background images Here’s how we do it for our advertisement.For brevity, only the unprefixed version is shown The bicycle image would be in-cluded similarly in eachbackground-imagedeclaration:
Trang 2rgba(0,0,0,0.06) 92%,
rgba(0,0,0,0) 98%);
background-position: 50% 88%, 0 0;
}
Note that we’ve put the bicycle picture first in the series of background images,
since we want the bicycle to sit on top of the gradient, instead of the other way
around We’ve also declared the background position for each image by putting
them in the same order as the images were declared in thebackground-image
property If only one set of values was declared—for example,background-position: 50% 88%;—all images would have the same background position as if you’d declaredbackground-position: 50% 88%, 50% 88%; In this case, the50% 80%positions
the bicycle, which was declared first, and the0 0(orleft top) positions the
gradient
Because a browser will only respect onebackground-imageproperty declaration
(whether it has one or many images declared), the bicycle image must be included
in eachbackground-imagedeclaration, since they’re all targeting different browsers.Remember, browsers ignore CSS that they fail to understand So if Safari doesn’t
understand-moz-linear-gradient(which it doesn’t), it will ignore the entire
This saves on bandwidth, of course, but it could also be beneficial if the heading
needed to stretch; a single image would be unable to accommodate differently sizedelements This time, we’ll use the background shorthand:
background:
url( /images/bg-formtitle-left.png) left 13px no-repeat,
url( /images/bg-formtitle-right.png) right 13px no-repeat;
Trang 3The background Shorthand
When all the available background properties are fully supported, the following two statements will be equivalent:
div {
background: url("tile.png") no-repeat scroll center
➥bottom / cover rgba(0, 0, 0, 0.2);
the shorthand altogether You must declare the shorthand before the longhand
properties, as any value not explicitly declared in the shorthand will be treated
as though you’d declared the default value.
Background Size
Thebackground-sizeproperty allows you to specify the size you want your ground images to have In theory, you can includebackground-sizewithin theshorthandbackgrounddeclaration by adding it after the background’s position,separated with a slash (/) As it stands, no browser understands this shorthand; infact, it will cause them to ignore the entirebackgrounddeclaration, since they see
back-it as incorrectly formatted As a result, you’ll want to use thebackground-sizeproperty as a separate declaration instead
Support forbackground-sizeis as follows:
■ Opera 11.01+:background-size(unprefixed)
Trang 4■ Safari and Chrome: current versions support unprefixed, but older versions quire-webkit-background-size
re-■ Firefox:-moz-background-sizefor 3.6,background-sizefor 4+
■ IE9:background-size
As you can see, adoption of the unprefixed version of this syntax was very quick;
it’s a simple property with a straightforward implementation that was unlikely to
change This is a great example of why you should always include the unprefixed
version in your CSS
If declaring the background image size in pixels, be careful to avoid the image torting; define either the width or the height, not both, and set the other value to
dis-auto This will preserve the aspect ratio of your image If you only include one
value, the second value is assumed to beauto In other words, both these lines havethe same meaning:
background-size: 100px auto, auto auto;
background-size: 100px, auto auto;
As with all background properties, use commas to separate values for each image
declared If we wanted our bicycle to be really big, we could declare:
-webkit-background-size: 100px, cover;
-moz-background-size: 100px, cover;
-o-background-size: 100px, cover;
background-size: 100px auto, cover;
By declaring just the width of the image, the second value will default toauto, andthe browser will determine the correct height of the image based on the aspect ratio.The default size of a background image is the actual size of the image Sometimes
the image is just a bit smaller or larger than its container You can define the size
of your background image in pixels (as shown above) or percentages, or you can
use thecontainorcoverkey terms
Thecontainvalue scales the image while preserving its aspect ratio; this may leaveuncovered space Thecovervalue scales the image so that it completely covers the
Trang 5element This can result in clipping the image if the element and its backgroundimage have different aspect ratios.
Screen Pixel Density, or DPI
The background-size property comes in handy for devices that have different pixel densities, such as the newest generation of smartphones For example, the iPhone 4 has a pixel density four times higher than previous iPhones; however,
to prevent pages designed for older phones from looking tiny, the browser on the
iPhone 4 behaves as though it only has a 320×480px display In essence, every
pixel in your CSS corresponds to four screen pixels Images are scaled up to
compensate, but this means they can sometimes look a little rough compared to the smoothness of the text displayed.
To deal with this, you can provide higher-resolution images to the iPhone 4 For example, if we were providing a high-resolution image of a bicycle for the iPhone,
it would measure 74×90px instead of 37×45px However, we don’t actually want
it to be twice as big! We only want it to take up 37×45px worth of space We can use background-size to ensure that our high-resolution image still takes up the right amount of space:
That’s all for CSS3 backgrounds and gradients In the next chapter, we’ll be looking
at transforms, animations, and transitions These allow you to add dynamic effectsand movement to your pages without relying on bandwidth- and processor-heavyJavaScript
Trang 68
CSS3 Transforms and Transitions
Our page is fairly static Actually, it’s completely static In Chapter 4 we learned alittle about how to alter a form’s appearance based on its state with the:invalidand:validpseudo-classes But what about really moving things around? Whatabout changing the appearance of elements—rotating or skewing them?
For years, web designers have relied on JavaScript for in-page animations, and theonly way to display text on an angle was to use an image This is far from ideal.Enter CSS3: without a line of JavaScript or a single JPEG, you can tilt, scale, move,and even flip your elements with ease
Let’s see how it’s done
Transforms
Supported in Firefox 3.5+, Opera 10.5, WebKit since 3.2 (Chrome 1), and even ternet Explorer 9, the CSS3transformproperty lets you translate, rotate, scale, orskew any element on the page While some of these effects were possible usingpreviously existing CSS features (like relative and absolute positioning), CSS3 givesyou unprecedented control over many more aspects of an element’s appearance
Trang 7In-We manipulate an element’s appearance using transform functions The value of
thetransformproperty is one or more transform functions, separated by spaces,which will be applied in the order they’re provided In this book, we’ll cover allthe two-dimensional transform functions WebKit also supports the transformation
of elements in 3D space—3D transforms—but that’s beyond the scope of this book
To illustrate how transforms work, we’ll be working on another advertisement block
from The HTML5 Herald, shown in Figure 8.1.
Figure 8.1 This block will serve to illustrate CSS3 transforms
Translation
Translation functions allow you to move elements left, right, up, or down Thesefunctions are similar to the behavior ofposition: relative;where you declaretopandleft When you employ a translation function, you’re moving elementswithout impacting the flow of the document
Unlikeposition: relative, which allows you to position an element either againstits current position or against a parent or other ancestor, a translated element canonly be moved relative to its current position
Thetranslate(x,y)function moves an element byxfrom the left, andyfrom thetop:
Trang 8If you only want to move an element vertically or horizontally, you can use the
translatexortranslateyfunctions:
<h1>Put your <span>dukes</span> up sire</h1>
Let’s apply the style whenever theh1is hovered over This will make the effect
more likely to be stumbled across than if it was only triggered by hovering over thespan itself:
Trang 9The result is shown in Figure 8.2.
Figure 8.2 The result of our translate transformIt’s nice, but we can still do better! Let’s look at how we can scale our text to make
it bigger as well
Scaling
Thescale(x,y)function scales an element by the defined factors horizontally andvertically, respectively If only one value is provided, it will be used for both thexandyscaling For example,scale(1)would leave the element the same size,scale(2)would double its proportions,scale(0.5)would halve them, and so on.Providing different values will distort the element, as you’d expect:
Trang 10A scaled element will grow outwards from or shrink inwards towards its center; inother words, the element’s center will stay in the same place as its dimensions
change To change this default behavior, you can include thetransform-origin
property, which we’ll be covering a bit later
Let’s add ascaletransform to our span:
css/styles.css (excerpt)
#ad3 h1:hover span {
color: #484848;
-webkit-transform: translateX(40px) scale(1.5);
-moz-transform: translateX(40px) scale(1.5);
-ms-transform: translateX(40px) scale(1.5);
-o-transform: translateX(40px) scale(1.5);
transform: translateX(40px) scale(1.5);
}
Note that there’s no need to declare a new transform—you provide it with a separated list of transform functions, so we just add ourscaleto the end of the list.It’s also worth remembering that scaling, like translation, has no impact on the
space-document flow This means that if you scale inline text, text around it won’t reflow
to accommodate it Figure 8.3 shows an example of how this might be a problem
In cases like this, you might want to consider simply adjusting the element’s height,width, or font-size instead of using a scale transform Changing those properties
will change the space allocated to the element by the browser
Figure 8.3 Using the scale function on inline text can have unwanted results
In our example, however, we want the text to pop out of the ad without reflowing
the surrounding text, so the scale does exactly what we need it to do Figure 8.4
shows what our hover state looks like with the scale added to the existing translation
Trang 11Figure 8.4 Our ad now has plenty of popIt’s looking good, but there’s still more to add.
Rotation
Therotate()function rotates an element around the point of origin (as withscale,
by default this is the element’s center), by a specified angle value Generally, anglesare declared in degrees, with positive degrees moving clockwise and negativemoving counter-clockwise In addition to degrees, values can be provided in grads,radians, or turns—but we’ll just be sticking with degrees
Let’s add arotatetransform to our “dukes”:
#ad3 h1:hover span {
color: #484848;
-webkit-transform:rotate(10deg) translateX(40px) scale(1.5);
-moz-transform:rotate(10deg) translateX(40px) scale(1.5);
-ms-transform:rotate(10deg) translateX(40px) scale(1.5);
-o-transform:rotate(10deg) translateX(40px) scale(1.5);
transform:rotate(10deg) translateX(40px) scale(1.5);
}
We’re rotating ourspanby ten degrees clockwise—adding to the effect of text that
has just been dealt a powerful uppercut We are declaring the rotation before the
translateso that it’s applied first—remember that transforms are applied in theorder provided Sometimes this will make no difference, but if an effect is behavingdifferently to what you’d like, it’s worth playing with the order of your transforms.The final transformed text is shown in Figure 8.5
Trang 12Figure 8.5 Our text has now been translated, scaled, and rotated—that’s quite a punch
There’s one more type of transform we’re yet to visit It won’t be used on The HTML5
Herald, but let’s take a look anyway.
Skew
Theskew(x,y)function specifies a skew along the X and Y axes As you’d expect,thexspecifies the skew on the X axis, and theyspecifies the skew on the Y axis
If the second parameter is omitted, theskewwill only occur on the X axis:
-webkit-transform: skew(15deg, 4deg);
-moz-transform: skew(15deg, 4deg);
-ms-transform: skew(15deg, 4deg);
-o-transform: skew(15deg, 4deg);
transform: skew(15deg, 4deg);
Applying the above styles to a heading, for example, results in the skew shown inFigure 8.6
Figure 8.6 Some text with a skew transform applied
As withtranslateandscale, there are axis-specific versions of the skew transform:skewx()andskewy()
Trang 13Changing the Origin of the Transform
As we hinted at earlier, you can control the origin from which your transforms areapplied This is done using thetransform-originproperty It has the same syntax
as thebackground-positionproperty, and defaults to the center of the object (sothat scales and rotations will be around the center of the box by default)
Let’s say you were transforming a circle Because the defaulttransform-originisthe center of the circle, applying arotatetransform to a circle would have no visibleeffect—a circle rotated 90 degrees still looks exactly the same as it did before beingrotated However, if you gave your circle atransform-originof10% 10%, youwould notice the circle’s rotation, as Figure 8.7 illustrates
Figure 8.7 Rotating a circle only works if the transform-origin has been setThe transform-originproperty is supported with vendor prefixes in WebKit,Firefox, and Opera:
-webkit-transform-origin: 0 0;
-moz-transform-origin: 0 0;
-o-transform-origin: 0 0;
transform-origin: 0 0;
Support for Internet Explorer 8 and Earlier
While CSS3 transforms are unsupported in IE6, IE7, or IE8, you can mimic theseeffects with other CSS properties, including filters To “translate,” useposition: relative;, andtopandleftvalues:
Trang 14This filter’s syntax isn’t worth going into here If you want to rotate an element in
Internet Explorer, go to http://css3please.com/ for cross-browser code for a given
rotation Just edit any of therotationvalues, and the other versions will be updatedaccordingly
Transitions
As much fun as it’s been to have a feature work in IE9, it’s time to again leave thatbrowser behind While Opera, Firefox, and WebKit all support CSS transitions, IE
is once again left in the dust
Transitions allow the values of CSS properties to change over time, essentially
providing simple animations For example, if a link changes color on hover, you
can have it gradually fade from one color to the other, instead of a sudden change
Trang 15Likewise, you can animate any of the transforms we’ve just seen, so that your pagesfeel more dynamic.
Animation has certainly been possible for some time with JavaScript, but nativeCSS transitions require much less processing on the client side, so they’ll generallyappear smoother Especially on mobile devices with limited computing power, thiscan be a lifesaver
CSS transitions are declared along with the regular styles on an element Wheneverthe target properties change, the browser will apply the transition Most often, thechange will be due to different styles applied to a hover state, for example However,transitions will work equally well if the property in question is changed usingJavaScript This is significant: rather than writing out an animation in JavaScript,you can simply switch a property value and rely on the browser to do all the heavylifting
Here are the steps to create a simple transition using only CSS:
1 Declare the original state of the element in the default style declaration
2 Declare the final state of your transitioned element; for example, in a hover state
3 Include the transition functions in your default style declaration, using a fewdifferent properties:transition-property,transition-duration,
transition-timing-function, andtransition-delay We’ll look at each ofthese and how they work shortly
The important point to note is that the transition is declared in the default state.Currently, the transition functions need to include the vendor prefixes-webkit-,-o-, and-moz-, for WebKit, Opera, and Firefox, respectively
This may be a lot to grasp, so let’s go over the various transition values As we go,we’ll apply a transition to the transforms we added to our ad in the last section, sothat the word “dukes” moves smoothly into its new position when hovered
transition-property
Thetransition-propertylists the CSS properties of the element that should betransitioned Properties that can be made to transition include background, border,and box model properties You can transition font sizes and weights, but not font
Trang 16families The W3C last updated the list of properties that can be transitioned in
August 2010:
■ background-colorandbackground-position
■ border-color,border-spacing, andborder-width
■ bottom,top,left, andright
■ clip
■ color
■ crop
■ font-sizeandfont-weight
■ heightandwidth
You can provide any number of CSS properties to thetransition-propertyation, separated by commas Alternatively, you can use the keywordallto indicatethat every supported property should be animated
declar-In the case of our ad, we’ll apply the transition to thetransformproperty:
#ad2 h1 span {
-webkit-transition-property: -webkit-transform;
-moz-transition-property: -moz-transform;