I had already written an article about this quite some time ago. The problem with this approach is that it only works with elements having a fix size. So I’ve written an article specific to the horizontal centering of variable width DIVs last year. The problem with this approach is that although it works I have no clue why and feel it might break some time in the future. Also this approach only works for centering horizontally. Luckily, since then, I’ve able to use another approach which seems cleaner and also doesn’t require my components to have a fix size and works both vertically and horizontally, without using any strange hacks.
Unfortunately, this will move the element past the center. You’ll also notice that it’s off by a lot vertically but less horizontally:
This is because margin-top doesn’t use the height of the container to compute percentages to pixels but just like margin-left, it uses the width. So if your container is square, you won’t see a difference but otherwise, it’s a problem. So using margin-top is no option. Instead, we’ll set the position to relative and set top to 50%. Ok, we’d implement it without hacks but this one not really a bad one…
This now looks better but it’s still not properly centered:
As you can probably guess now, the problem is that the upper left corner of the element is centered both vertically and horizontally. Not the center of the element. In order to correct this, we need some CSS properties which unlike the margin-xxx or top do not take into account the dimensions of the container but the dimensions of the element. Actually there aren’t so many properties like this. Luckily CSS transformations do work with the dimensions of the element. So a translation of -50% both vertically and horizontally will center the element:
I guess most web sites are now using CSS to create nice looking buttons without using background images. Google has done a nice job creating clean looking buttons. I’ll show in this article how you can easily create similar looking buttons.
First regarding why it makes sense to use only CSS to create buttons instead of using background images:
The browser does not need to load images. This makes the page loading process faster.
It makes it easier to create scalable buttons which look good no matter how long the label on the button.
You just need to adapt the CSS style in order to get different styles of buttons.
As far as I could see, Google seems to be using 4 types of buttons in Google Plus:
Add
Save
Add
Post comment
First we’ll style the first button as our default button (the one with the white background):
The user-select: none properties are used to prevent text selection (the browser doesn’t know it’s a button).
Also the rounded corners will be square in Internet Explorer 8 and lower as well as in Opera Mini. And the box shadows will be missing in these browsers too.
Also note that I’m using the default cursor for the button because it’s the way it is in Google Plus. But if you’d rather have the pointer cursor used for links, just replace:
cursor: default;
by:
cursor: pointer;
You might have noticed that the labels on the buttons look a little bit different than on Google Plus, because they use the Roboto font. If you want to use it, you’ll need to get it from Google Fonts. But I personally use Arial which is close enough and has the advantage of already being available pretty much on every machine without having to reference an external resource which can have an impact on page load time. Anyway, in order to use the Roboto font, add the following code to the <head> tag of your website:
These buttons use the usual Google colors. But you can of course define colors which will better fit to the styles of your website but still provide the clean and polished look of the Google Plus buttons e.g.:
Feel free to leave a comment if you spot a problem, have a suggestion how to improve them or just like them.
Note that this currently only works with Firefox. Support for Chrome and Internet Explorer is not yet available and it’s not yet known when it will be available.
The new Battery Status API allows you from a web page to access information about the battery status of the device rendering it. It is not only useful in order to show the current status but to implement battery status dependent logic e.g. increasing polling interval using Ajax or disabling animations in order to preserve the battery, or auto-saving in case the device goes out of power, prevent the user from performing long running operation which might not be able to finish because of the low remaining battery level.
First we’ll create the HTML and CSS in order to get an empty battery display looking like this:
The HTML code couldn’t be simpler. We just need a battery div:
<div id="battery"></div>
Now we need to display a border around the div and a smaller rectangle after it:
By setting the width of .battery-level in pixels (or in percent which is the same since the element is 100 pixels wide) to the battery level in percents, we’ll get the right display:
Of course, one would expect our battery level display to show the level in a different color depending whether the battery is almost empty or not. So let’s introduce three CSS classes which will show the level in green, yellow or red:
Before we move to the HTML5 part, let’s also display the battery level as text, by setting it as text on the battery-level element and by adding the following css rule:
.battery .battery-level {
text-align: center;
}
It then looks like this:
10%
75%
95%
Now we’re almost done… All we need is what’s actually the main topic of this post: to get the battery level data using HTML5. For this we need to use the new Battery Status API.
The Battery Status API provides access the battery information through navigator.battery which implement the BatteryManager interface. This interface provides the following information:
whether the battery is currently charging
the charging time
the discharging time
the battery level
Additionally, it also provides events you can listen to:
onchargingchange
onchargingtimechange
ondischargingtimechange
onlevelchange
We will not use the events for now and just show the battery level when the page was loaded:
The JavaScript code to work with this API is pretty straight forward:
var battery = navigator.battery;
var level = battery.level * 100;
var batteryLevel = jQuery('.battery .battery-level');
batteryLevel.css('width', level + '%');
batteryLevel.text(level + '%');
if (battery.charging) {
batteryLevel.addClass('charging');
} else if (level > 50) {
batteryLevel.addClass('high');
} else if (level >= 25 ) {
batteryLevel.addClass('medium');
} else {
batteryLevel.addClass('low');
}
If you want to update the battery level display as the battery charges and discharges:
Here’s the JavaScript code:
function updateBatteryDisplay(battery) {
var level = battery.level * 100;
var batteryLevel = jQuery('.battery .battery-level');
batteryLevel.css('width', level + '%');
batteryLevel.text(level + '%');
if (battery.charging) {
batteryLevel.addClass('charging');
batteryLevel.removeClass('high');
batteryLevel.removeClass('medium');
batteryLevel.removeClass('low');
} else if (level > 50) {
batteryLevel.addClass('high');
batteryLevel.removeClass('charging');
batteryLevel.removeClass('medium');
batteryLevel.removeClass('low');
} else if (level >= 25 ) {
batteryLevel.addClass('medium');
batteryLevel.removeClass('charging');
batteryLevel.removeClass('high');
batteryLevel.removeClass('low');
} else {
batteryLevel.addClass('low');
batteryLevel.removeClass('charging');
batteryLevel.removeClass('high');
batteryLevel.removeClass('medium');
}
}
var battery = navigator.battery;
updateBatteryDisplay(battery);
battery.onchargingchange = function () {
updateBatteryDisplay(battery);
};
battery.onlevelchange = function () {
updateBatteryDisplay(battery);
};
So the Battery Status API is a very powerful and useful API which is very easy to use. Now let’s hope it will soon be available in all major browsers !
I recently noticed a few problems in some code I had written a few months ago:
I am displaying a grid containing an empty first column and an empty last column and want to remove them. This only happened for the first row and not for the others
I display a left border on all columns and additionally a right border on the last column. This also didn’t work anymore, the right border was missing.
These two problems were due to using the selector (once in CSS and once with jQuery) which do not do what I would expect.
First let’s assume we have a table-like div structure:
Well the problem is that is that it only worked by chance and as soon as I extended the generated html code, it broke. I needed to add some additional divs at the end of every line in the grid but have them be invisible. So basically, since the new divs where invisbile, the current last div would still have to be styled in a special way although it wasn’t the last div child anymore. So I just modified my CSS and jQuery selectors like this:
div.tr div.td:last-child { }
jQuery("div.tr div.d:last-child")
And the same for th as well. But it doesn’t work. What happens is that div.tr div.td:last-child doesn’t mean select the last child of div.tr being a div.td. It means select the last child of div.tr if it is a div.td. So since the last child of div.tr was not a div.td anymore, it failed.
So what I needed was a selector like :last-child-of-type. Well actually there is a selector :last-of-type. Unfortunately, it also failed using it since this selector doesn’t work with classes i.e. you can use div:last-of-type as selector but not div.class:last-of-type. So :last-of-type is useful to select the second div in this case:
But not in our case. So what can be done ? Well, the way I went for (which just involved replacing an append by a prepend) was to move the hidden divs to the beginning of the row. So now I could use :last-child again. And since I was selecting the first line only with jQuery, I used the following:
So it’d be great if :last-of-type could support classes or if there was a :last-of-class. But until there is, you can work around it with jQuery using a loop. In CSS, unfortunately, there seems to be no way to do it. The only way to select this last element of a type using CSS selectors is to assign it a class with javascript or while generating the HTML code and then selecting this class using CSS.
When centering divs, if your div has a fixed width you can either absolutely position it and set negative margins as shown in this post. Another way to center such a fixed width div horizontally is to set both its left and right margin to auto. The browser then has to set both margins to the same value.
Unfortunately known of these two techniques can be used if your div doesn’t have a fixed width. In this case, you’ll need a different solution.
Let’s assume you have a container div with another div inside:
The container div will fill the whole window while the contained div will fill the upper left corner:
The trick is to set a centered text alignment on the container and set an inline-block display on the contained div. Of course the text-align CSS property will be inherited by the contained div so you’ll need to set it back to left:
I actually found it while changing all possible properties on the container and contained div. Just by chance. It still doesn’t make much sense to me but it does work. Before figuring this out, I was always using some JavaScript to find out the actual width of the contained div and set the margins accordingly and recomputing it on any resize. In case you are still interested in a jQuery solution, please check Manos Malihutsakis Blog.
I’ve added a new tool to my online tool collection. It’s a CSS minifier. Click here to access it.
What’s a CSS minifier ?
The purpose of this tool is to reduce the size of CSS code without changing the way it works. It just gets rid of things a browser doesn’t use anyway like:
comments
empty rulesets
empty @font-face, @media and @page at-rule blocks
extra spaces
line breaks
It also converts a few few things to save a few extra bytes:
font weight values normal to 400 and bold to 700
color values in hsl notation to hexadecimal notation
color values in rgb notation to hexadecimal notation
named color values to hexadecimal notation
compresses color values in hexadecimal notation if possible e.g. #ffffff to #fff
compresses unit values
The CSS code produced by this tool is not very human-readable anymore but it is compacter and the saved size will reduce the bandwidth used when loading your page.
Why should I care ?
Minifying CSS speeds up the downloading of your web page. Why should you care ? Does anybody like to wait for a web page to load ? Probably not. Will many visitors hit the Back button before a slow page has been loaded. Probably. So even though minifying CSS alone will not make a slow page fast, it’s one of the things you can do to speed up your page. And since you can use this online tool to get the minified CSS, it’s really easy.
Copy the CSS code you want to minify, click here, enter your CSS code in the text area titled “CSS to be minified”, select the options you want to use and click on the “Minify” button.
The minified code will then be displayed in the text area titled “Minified CSS”. You can copy it and paste it back to your CSS or HTML file replacing the existing CSS code.
Did you write everything from scratch ?
No. This tool wraps the excellent cssmin PHP library by Joe Scylla.
It provides you with the possibility to set many properties, see how the results would look like, change the properties until it looks right and then copy the CSS code to paste on your site.
It supports the following properties:
You can see the results in a preview:
In this example, the preview shows how it looks like When entering 20px as top left border radius, 5px as top border width, dashed as top border style and #333 as top border color.
Below the preview, it will display the corresponding CSS code:
THe CSS z-index property is a very useful one but it’s not used very much in many websites. The purpose of this property is to achieve something like:
Screenshot of Windows 2.0 – Used with permission from Microsoft.
Or like this:
Screenshot of System 6
So the purpose of the CSS property z-index is to absolutely position an HTML element on top of the other elements on the screen. This is mostly useful to implement dialogs, information or navigation banners, information bubbles, light boxes, menus, . The contents below the element shown on a higher layer are not visible or only partially visible.
How does the world look like without z-index ?
Without the z-index property, the stacking of HTML elements still happens. It’s just much difficult to control it. The elements are positioned using a default stacking order:
Background and borders of the root element
Non-positioned, non-floating block elements in the order they appear in your code
Non-positioned floating block elements in the order they appear in your code
Non-positioned inline elements in the order they appear in your code
Positioned elements in the order they appear in your code
Even though you can still somehow figure out how to position the elements in the code and assign positioning in order to help, it’s clearly a waste of time and I doubt most web developers can actually really figure it out without a lot of trial and error.
So the summary is that if you want to display overlapping components in a specific stacking you need to use the CSS z-index property.
So how do I use it ?
There is nothing easier: just add the following CSS property to a rule matching an element:
z-index: 10
Instead of 10 you can use any other integer value. If you use a negative value, it will be displayed below all non-positioned, non-floating block elements but above the background and borders of the root element.
So it’s fairly easy. But there are a few things you have to know about it.
The first one is that z-index only works on elements which do not have a static position i.e. one of the following:
Additionally to an integer number you can also use auto. The element will then get the same stack order as its parent.
You should also keep in mind that it is important how the elements are nested. A child element can never be higher that the elements which are higher than its parent.
A few examples please…
Here are a few example to help you understand how stacking works with and without z-index.
This new tool can be used to create some CSS styling for text. It looks like this:
You can enter the text you want to style in the upper text area and then select in the lower part of the UI which attributes you want to set. It currently supports the following:
Font family: It provides a list of web safe fonts you can select from
Font size: You can define a font size in “ems” (em: scalable unit based on the current font size), pixels (px), points (pt: fixed-size units used in print media) or percents (%: scalable unit similar to ems)
Background color
Foreground color
Bold and/or italic
Underline, Strikethrough or none
All caps (uppercase), capitalized (similar to Camel-Case) or none
Left, center, right alignment or justified
Letter and word spacing
Wrapping
Every time you change some of the properties in the lower pane, you will see that the text styling changes to reflect this and the corresponding CSS properties are shown in the text area in the middle.
There are a few more things that I still need to add:
Leading spaces
Line height
Border size, color and style
Text and box shadow
Corners
Lower case and small caps
Oblique
Overline
Margin and padding
Width and height
Indentation
Kerning
Writing direction
Vertical alignment
Containing tag (e.g. div, span, p)
Hope you enjoy the tool ! Feel free to leave a comment below in case you see something wrong or have a suggestion how to further improve the tool.
Checkboxes are kind of the most boring elements on a web page since the browsers always display them the same. Another problem is that the checkbox itself is pretty small. Of course it’s not a real problem for such checkboxes:
You can click on the checkbox itself or on the label to toggle it. So the small size of the checkbox itself is not an issue. But when you have something like this, it’s more of a problem:
Identification code:
Display name:
Activated:
Even if you wrap the checkbox in a label for it, you can still click anywhere near the checkbox to toggle it but it’s not visible to the user that it’s possible.
A better solution would be to have some alternative representation of the checkbox e.g. as a switch. It’s also important to be able to adapt the size of the switch. Here’s how it should look like in the end (the first one is the normal size and the second one is twice as large):
Since you cannot style the checkbox itself, we’ll have to add a new element and hide the checkbox. Additionally, since some scripts will read the state of the checkbox, we need to keep the checkbox in there (even if not displayed) and we need to make sure that the state of the switch and the state of the check are in sync.
The easiest way to do it is to use a label. As can be see above if a label is created for a checkbox, clicking on the label toggles the checkbox. So the basic idea is to:
add a label for the checkbox
hide the checkbox
style the label to look like a switch
have a styling of the label based on the state of the checkbox
For the last point, we’ll leverage a special kind of CSS selector which selects elements that are placed immediately after a given element. This is done with a plus sign between the two elements:
input[type="checkbox"] + label
This would select the labels immediately following a checkbox. Using this we can style the labels depending on the state of the checkbox.
Note that I’ve used the class “switch” in case you do not want to turn all checkboxes into switches but only some of them. If you do want to turn them all into switches, just remove this class from all selector in the CSS and jQuery code in the rest of this post.
Your checkbox should also need to have an ID to be referenced by the label. Now let’s add the label dynamically using jQuery:
Search for all checkboxes to be turned into switches
Only change the ones with an ID
Add a label immediately after the checkbox referencing the ID of the checkbox
Note that we do not need a special class for the label as we need to make the appearance dependent on the checkbox state anyway so no extra selector for the label is required.
If you want to achieve a solution without JavaScript, you’ll have to add the label after the checkbox manually in the HTML code e.g.:
I’d rather use JavaScript and CSS pseudo-classes than polute my HTML code with elements which are only needed for styling. But I guess others may see it in a different way and rather use pure CSS and HTML than introduce some JavaScript.
Now we have this all in place, we just need to style the checkboxes and labels. An easier way to do it would be to use a background image. But I tend to avoid using images except for icons. And also if the element has to have a variable size, I definitely try to avoid images. The goal in this post is anyway no do show you how to make nice looking backgrounds with CSS only so we’ll stick to a plain two color background.
The first step is to hide the checkboxes we’ll turn into switches:
input[type="checkbox"].switch {
display: none;
}
Now we want the label to look like a switch, so have a border, be rounded on the left and right and have a background color depending on its state (e.g. red for not checked and green for checked):
For the border radius, you’ll need to add the following to make it work in older browsers (i.e. Firefox < 4.0, Chrome < 5.0, Safari < 5.0, iOS Safari < 4.0 and Android Browser < 2.2):
Please also note that IE only supports it starting with version 9.0.
The inline-block is a great invention. For those who still don’t know it, it’s a kind of float on steroids. It means it handles width and height just like a block element. But is displayed inlined with the surrounding elements just like inline elements. So this means that the label will have a width and height although it doesn’t have a text and that the round element we’ll add afterwards will be displayed in it.
Note that we’ve defined the width in ems. This allows us to make the element scale when we increase the font size.
Now, we’ll use pseudo-classes to dynamically add a round element which will be moved from left to right when the checkbox is checked:
So the content is empty because we do not want to display some text but only have a background and borders displayed.
box-sizing is used so that the width and height defined do already contain the borders. We want this element to be half the width of the containing label and to be round (so same height and width). Since the width of the label is defined in ems, the height and width of this element also have to be defined in ems. But since we need the border to always be 1 pixel (defining it also in ems makes it look terrible when the size is increased), we should define the width and height to be 0.8em – 1px. This is not possible. So we use box-sizing to say that the 0.8em already contains the border.
Note that box-sizing, requires a prefix for all versions of Firefox (both mobile and desktop) and required a prefix for Safari until version 5.0, for iOS Safari until version 4.3, for Blackberry Browser version 7.0, Android Browser until version 3.0. Also not that Internet Explorer version 7.0.
When the checkbox is checked, we want to change the background color and move the round element to the right. Changing the background color is easy. The trick to move it to the right is to add a padding to the label. But adding the padding will make the label larger so at the same time we have to reduce the width of the label:
So now the switch is working ! But we want the transition to be smoother when the checkbox is checked or unchecked. This is done with the transition-duration and transition-property CSS properties:
This means that when changing the padding and width the transition will be distributed over 300 milliseconds. You could also add the change of background color but I felt it looks kind of strange because it looks like it changing to some kind of brownish color between red and green. Also, for this CSS property there are also browser specific prefixes: