1.Centre aligning a block element
Say you wanted to have a fixed width layout website, and the content floated in the middle of the screen. You can use the following CSS command:
#content
{
width: 700px;
margin: 0 auto;
}
You would then enclose
<div id="content">
around every item in the body of the HTML document and it'll be given an automatic margin on both its left and right, ensuring that it's always placed in the centre of the screen. Simple... well not quite - we've still got the pre-IE 6 versions to worry about, as these browsers won't centre align the element with this CSS command. You'll have to change the CSS rules:body
{
text-align: center;
}
#content
{
text-align: left;
width: 700px;
margin: 0 auto;
}
This will then centre align the main content, but it'll also centre align the text! To offset the second, probably undesired, effect we inserted
text-align: left
into the content div.2. Vertically aligning with CSS
Vertically aligning with tables was a doddle. To make cell content line up in the middle of a cell you would use
vertical-align: middle
. This doesn't really work with a CSS layout. Say you have a navigation menu item whose height is assigned 2em and you insert this vertical align command into the CSS rule. It basically won't make a difference and the text will be pushed to the top of the box.
Hmmm... not the desired effect. The solution? Specify the line height to be the same as the height of the boxitself in the CSS. In this instance, the box is 2em high, so we would insert
line-height: 2em
into the CSS rule and the text now floats in the middle of the box - perfect!3. CSS positioning within a container
One of the best things about CSS is that you can position an object absolutely anywhere you want in the document. It's also possible (and often desirable) to position objects within a container. It's simple to do too. Simply assign the following CSS rule to the container:
#container
{
position: relative
}
Now any element within this container will be positioned relative to it. Say you had this HTML structure:
<div id="container"><div id="navigation">...</div></div>
To position the navigation exactly 30px from the left and 5px from the top of the container box, you could use theseCSS commands:
#navigation
{
position: absolute;
left: 30px;
top: 5px
}
Perfect! In this particular example, you could of course also use
margin: 5px 0 0 30px
, but there are some cases where it's preferable to use positioning.
No comments:
Post a Comment