CSS Appropriate Way to Center Content - css

I prefer working with CSS based design, but as more of a back end coder my CSS skills are a bit weak. When I get involved with layout, I tend to fall back on table based formatting because my mind has been warped by years of table based abuse. There's one particular problem that I always trip over. What is the best CSS alternative to:
<table width="100%">
<tr>
<td align="center">
content goes here
</td>
</tr>
</table>
I sometimes use:
<div style="width:100%; text-align:center">content</div>
But this doesn't seem quite right. I'm not trying to align text, I'm trying to align content. Also, this seems to have an effect on the text alignment of enclosed elements, which requires tweaking to fix. One thing I don't get is: why isn't there a float:center style? It seems like that would be the best solution. Hopefully, I'm missing something and there is a perfect CSS way to do this.

You are right that text-align is intended for aligning text. It's actually only Internet Explorer that lets you center anything other than text with it. Any other browser handles this correctly and doesn't let block elements be affected by text-align.
To center block elements using css you use margin: 0 auto; just as Joe Philllips suggested. Although you don't need to keep the table at all.
The reason that there is no float: center; is that floating is intended to place elements (typically images) either to the left or the right and have text flow around them. Floating something in the center doesn't make sense in this context as that would mean that the text would have to flow on both sides of the element.

I would recommend putting a <div> into your <td> and setting the style attribute to style="width: 200px; margin: 0 auto;"
The catch is that you must set a fixed width.
Edit:
After looking at the question again, I would recommend scrapping the table entirely. Just use a <div style="width: 200px; margin: 0 auto;> as I suggested and no need for a table.

Here is a good resource for centering using CSS.
http://www.w3.org/Style/Examples/007/center
This demonstrates how to center text, blocks, images and how to center them vertically.

Where do you find yourself commonly doing this? For me - I am most often trying to center the entire design of the site, so I usually do this:
<html>
<body>
<div id="wrapper">
<div id="header">
</div>
<div id="content">
</div>
<div id="footer">
</div>
</div>
</body>
</html>
body {text-align:center;}
#wrapper {margin:0 auto; text-align:left; width:980px;}
This will center the entire design on the page at 980px width, while still leaving all of your text left aligned (as long as that text is within the #wrapper element).

Use display:inline-block to enable text-align:center and center content without a fixed width:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Centering</title>
<style type="text/css">
.container { text-align:center; }
/* Percentage width */
.wrapper { width: 99%; }
/* Use inline-block for wrapper */
.wrapper { display: inline-block; }
/* Use inline for content */
.content { display:inline; }
</style>
</head>
<body>
<div class="container">
<div class="content">
<div class="wrapper">
<div>abc</div>
<div>xyz</div>
</div>
</div>
</div>
</body>
</html>

d03boy's answer is correct for the right way to center things.
To answer your other comment, "Also, this seems to have an effect on the text alignment of enclosed elements, which requires tweaking to fix." That's the nature of how CSS works, setting a property on an element affects all of its children, unless the property is overridden by one of them (assuming the property is one that is inherited, of course).

Related

side by side <div> and site centering

I'm trying to convert my site from using tables to just using css and divs but I'm running into a lot of problems with trying to figure how to exactly do it, I've been looking for tutorials on centering a site with css and how to put divs side by side but I can't really find one that does both and I keep getting confused by how to exactly achieve this, I asked around a bit and I got told to use absolute positioning but still I can't really wrap my head around this.
So basically how would I arrange the 2 central div side by side while keeping the whole thing centered in the browser? The following image is the layout I'm trying to achieve:
the blue boxes are eventual other stuff I might want to put in them, such as a blog requiring again the use of side by side divs.
right now I have the following layout:
<div id="wrap">
<div id="banner"> banner </div>
<div id="navbar"> navigation links </div>
<div id="body"> stuff </div>
<div id="footer"> stuff </div>
</div>
General idea: http://jsfiddle.net/JjbJE/
A little specific but provide you a great adventure to learn HTML | CSS : http://jsfiddle.net/JjbJE/3/
float:left|right this property does the side by side trick
clear:both this property clear away the float property
Other things are pretty easy to learn, just head to W3Schools
First you need a main container to center everything. Then two separate divs. See the HTML below:
<div id="main">
<div class="box">Left Box</div>
<div class="box">Right Box</div>
<div class="clear"></div>
</div>
Here is the CSS you will need:
#main{
width:960px;
margin:0 auto;
}
.box{
width:450px;
float:left;
border:solid 1px #000000;
}
.clear{
clear:both;
}
Hope that helps.
Here's my general overview on converting to a CSS based layout - if you have a table based layout, this is a good plan - in the end you can do more, Google will like you more, and it's much cooler.
My strategy is to look at all the groups of things on your page. Whatever needs to go into a group together, put inside a div. Assign this div a class and/or id to style it. If the divs are grouped, put them together in a div too.
In your case, you have two chunks of content to group inside of divs. Style them to be the size and shape you like, background, border, whatever is needed. Then group them together in an additional div, and center it. This and the rest of the page content can go inside a container div, which will determine the width of the page, how it's aligned, etc.
One possibility is to have a centered wrapper class and contain the divisons inside of that:
<div class="wrapper">
<header></header>
<div id="middle">
<div class="main-article clearfix"></div>
<aside></aside>
</div>
<footer></footer>
</div>
Then to style, center the wrapper, float the aside and main-article:
.wrapper { width: 1024px; margin: 0 auto; /* the auto centers it */ }
header, footer, aside, { display: block; }
.main-article { width: 50%; float: right; }
aside { width: 50%; float: left; }
.clearfix:before, .clearfix:after { content: ""; display: table; }
.clearfix:after { clear: both; }
.clearfix { *zoom: 1; }
Note: This is untested, and uses the clearfix from the HTML5 Boilerplate.
Update 01.22.2014: This "Holy Grail Layout" has ben solved by Flexbox. Check out Solved By Flexbox for more information on recreating this layout (and many more).

Two div element next to each other (For page header)

I am trying to make something look like following (don't concern color here. my concern here is the shape);
I tried something with following code but didn't succeed!
<html>
<head>
<style type="text/css">
#header{border:3px solid gray;padding:10px;}
#header-left-container{border:1px solid gray;float:left;width:30%;}
#header-right-container{border:1px solid gray;float:right;width:69%;}
</style>
</head>
<body>
<div id="header">
<div id="header-left-container">
pooo
</div>
<div id="header-right-container">
bla bla bla.....
</div>
</div>
</body>
</html>
I know this can be done with table easily but I don't wanna use table in my application where I can do the same with div elements.
any suggestion here?
http://jsfiddle.net/j4DnG/7/
What you need to do is clearing the area arround the 2 floated divs.
Doing this by modern technuiqe is giving the parent the property of Overflow:Hidden or Auto (what ever fitting you more. I recommend hidden)
In the past people user clearfix (google on that). Todays we use that approach.
As well people used to put clear:both after the creation of the two elements. That has a negative side- 1 more element in the dom.
You need to add overflow:auto; to the #header css; without that divisions don't expand to contain floated elements.
your code looks fine...
suggestions:
Just Add clearfix after floating divs so as they will be contained inside the parent object like:
<style>.clarFix{clear:both;}</style>
<div class="clearfix"></div>
Add
<br style="clear:both" />
after second div. Or make the container div float: left. Or use one of the css frameworks if You don't want to become css master before You create a webpage. One is http://960.gs/
Do you use firebug? go on twitter.com and see how they have defined a left and a right container is the style sheet . They're not using table to implement it. just div
Just replace the float: right; declaration with a margin-left: 30%; declaration for #header-right-container. You don't need to float both of them. This way, you will only need to clear floats if the left block is taller than the right block. See this fiddle.

Centering 2 divs of unknown width in IE6 and IE7

OK so what would happen if I have 2 divs (one containing text, the other an image). The image always has a static width but the text varies. hence making its containing div variable.
I can make it work for all other browsers (except IE6 and IE7) by using CSS display:table. IE6 and 7 don't have that so I can't find a workable solution to center them all.
... so you know what I'm talking about...
.container{text-align:center; width:100%}
.container .centered{display:table; margin:0 auto}
<div class="container">
<div class="centered">
<div id="text">varying length text</div>
<div id="image">IMAGE</div>
</div>
</div>
Quite apart from the lack of IE support, setting display: table as you have without its children using display: table-row/table-cell results in undefined behaviour. It doesn't make sense to put block elements directly inside a table element and the browser might do anything at all.
What you are trying to do is get shrink-to-fit width behaviour without using float, which is a normal way of getting shrink-width but requires that the block in question goes to the left or right not centre. Probably a better way of saying that would be to use an inline-block:
.centered { text-align: center; }
.centered span { display: inline-block; border: dotted red 1px; }
<div class="centered">
<span id="text">varying length text</span>
</div>
<div class="centered">
<span id="image">IMAGE</span>
</div>
(You have to use a naturally-inline element like span to make it work under IE<8; div would fail. There is also -moz-inline-box if you need to target Firefox 2.)
Are you using quirksmode or standards compliant mode? In other words have you included a DOCTYPE declaration at the top of your html page?
You shouldn't need to use display:table just margin:auto should do the trick provided you are using a standards mode.

CSS layout, use CSS to reorder DIVs [duplicate]

This question already has answers here:
How can I reorder my divs using only CSS?
(27 answers)
Closed 6 years ago.
Given that the HTML
<div>
<div id="content1"> content 1</div>
<div id="content2"> content 2</div>
<div id="content3"> content 3</div>
</div>
render as
content 1
content 2
content 3
My question:
Is there a way to render it as below by using CSS only without changing the HTML part.
content 1
content 3
content 2
This can be done in browsers that support the CSS3 flexbox concept, particularly the property flexbox-order.
See here
However, support for this is only in current versions of most browsers still.
Edit Time moves on and the flexbox support improves..
This works for me:
http://tanalin.com/en/articles/css-block-order/
Example from this page:
HTML
<div id="example">
<div id="block-1">First</div>
<div id="block-2">Second</div>
<div id="block-3">Third</div>
</div>
CSS
#example {display: table; width: 100%; }
#block-1 {display: table-footer-group; } /* Will be displayed at the bottom of the pseudo-table */
#block-2 {display: table-row-group; } /* Will be displayed in the middle */
#block-3 {display: table-header-group; } /* Will be displayed at the top */
As stated there, this should work in most browsers. Check link for more info.
It might not exactly match what you're after, but take a look at this question:
CSS positioning div above another div when not in that order in the HTML
Basically, you'd have to use Javascript for it to be reliable in any way.
This is one of the classic use-cases for absolute positioning--to change rendering from source order. You need to know the dimensions of the divs to be able to do this reliably however, and if you don't javascript is your only recourse.
I was messing around in Firefox 3 with Firebug, and came up with the following:
<div>
<div id="content_1" style="height: 40px; width: 40px; background-color: rgb(255, 0, 0); margin-bottom: 40px;">1</div>
<div id="content_2" style="width: 40px; height: 40px; background-color: rgb(0, 255, 0); float: left;">2</div>
<div id="content_3" style="width: 40px; height: 40px; background-color: rgb(0, 0, 255); margin-top: -40px;">3</div>
</div>
It's not perfect, since you need to know the heights of each container, and apply that height value to the negative top margin of the last element, and the bottom margin of the first element.
Hope it helps, nd
I got it to work by doing this:
#content2 { position:relative;top:15px; }
#content3 { position:relative; top:-17px; }
but keep in mind that this will not work for you as soon as you have dynamic content. The reason I posted this example is that without knowing more specific things about your content I cannot give a better answer. However this approach ought to point you in the right direction as to using relative positioning.
One word answer: nope. Look into XSLT (XML Stylesheet Language Transforms), which is a language specifically geared towards manipulating XML.
If you know the height of each element then it is a simple case of vertical relative positioning to swap around the orders. If you don't know the heights then you either have to give them heights and allow the divs to get scroll bars if there is any overflow or calculate it all with JavaScript and add the relative positioning on-the-fly.
with jquery you can simply do:
$('#content2').insertAfter($('#content3'));
I don't think there's a way to do it with CSS, except to force fixed positioning of each of the divs and stack them that way.

How to position two divs horizontally within another div

I haven't played with CSS for too long a time and am without references at the moment. My question should be fairly easy but googling isn't bringing up a sufficient answer. So, adding to the collective knowledge...
|#header---------------------------------------------------------------|
| TITLE |
|#sub-title------------------------------------------------------------|
|bread > crumb | username logout |
|#sub-left | #sub-right|
|---------------------------------|------------------------------------|
That's what I'm wanting my layout to be. The heading anyways. I wanted sub-title to contain sub-left AND sub-right. What css rules do I use to ensure a div is bound by the attributes of another div. In this case, how do I ensure that sub-left and sub-right stay within sub-title?
Its quite a common misconception that you need a clear:both div at the bottom, when you really don't. While foxy's answer is correct, you don't need that non-semantic, useless clearing div. All you need to do is stick an overflow:hidden onto the container:
#sub-title { overflow:hidden; }
When you float sub-left and sub-right they no longer take up any space within sub-title. You need to add another div with style = "clear: both" beneath them to expand the containing div or they appear below it.
HTML:
<div id="sub-title">
<div id="sub-left">
sub-left
</div>
<div id="sub-right">
sub-right
</div>
<div class="clear-both"></div>
</div>
CSS:
#sub-left {
float: left;
}
#sub-right {
float: right;
}
.clear-both {
clear: both;
}
This should do what you are looking for:
<html>
<head>
<style type="text/css">
#header {
text-align: center;
}
#wrapper {
margin:0 auto;
width:600px;
}
#submain {
margin:0 auto;
width:600px;
}
#sub-left {
float:left;
width:300px;
}
#sub-right {
float:right;
width:240px;
text-align: right;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="header"><h1>Head</h1></div>
<div id="sub-main">
<div id="sub-left">
Right
</div>
<div id="sub-right">
Left
</div>
</div>
</div>
</body>
</html>
And you can control the entire document with the wrapper class, or just the two columns with the sub-main class.
I agree with Darko Z on applying "overflow: hidden" to #sub-title. However, it should be mentioned that the overflow:hidden method of clearing floats does not work with IE6 unless you have a specified width or height. Or, if you don't want to specify a width or height, you can use "zoom: 1":
#sub-title { overflow:hidden; zoom: 1; }
This answer adds to the solutions above to address your last sentence that reads:
how do I ensure that sub-left and sub-right stay within sub-title
The problem is that as the content of sub-left or sub-right expands they will extend below sub-title. This behaviour is designed into CSS but does cause problems for most of us. The easiest solution is to have a div that is styled with the CSS Clear declaration.
To do this include a CSS statement to define a closing div (can be Clear Left or RIght rather than both, depending on what Float declarations have been used:
#sub_close {clear:both;}
And the HTML becomes:
<div id="sub-title">
<div id="sub-left">Right</div>
<div id="sub-right">Left</div>
<div id="sub-close"></div>
</div>
Sorry, just realized this was posted previously, shouldn't have made that cup of coffee while typing my reply!
#Darko Z: you are right, the best description for the overflow:auto (or overflow:hidden) solution that I have found was in a a post on SitePoint a while ago Simple Clearing of FLoats and there is also a good description in a 456bereastreet article CSS Tips and Tricks Part-2. Have to admit to being too lazy to implement these solutions myself, as the closing div cludge works OK although it is of course very inelegant. So will make an effort from now on to clean up my act.
Seriously try some of these, you can choose fixed width or more fluid layouts, the choice is yours! Really easy to implement too.
IronMyers Layouts
CSS Layouts
Layouts Customization Guide
750 Pixel CSS Layouts
950 Pixel CSS Layouts
100 Percent CSS Layouts
more more more
Layout Gala CSS Layouts
Glish CSS Layouts
Code Sucks CSS Layouts
Max Design CSS Layouts
CSS Play CSS Layouts
You can also achieve this using a CSS Grids framework, such as YUI Grids or Blue Print CSS. They solve alot of the cross browser issues and make more sophisticated column layouts possible for use mere mortals.
Best and simple approach with css3
#subtitle{
/*for webkit browsers*/
display:-webkit-box;
-webkit-box-align:center;
-webkit-box-pack: center;
width:100%;
}
#subleft,#subright{
width:50%;
}
Something like this perhaps...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<style>
#container
{
width:600px;
}
#head, #sub-title
{
width:100%;
}
#sub-left, #sub-right
{
width:50%;
float:left;
}
</style>
</head>
<body>
<div id="container">
<div id="head">
#head
</div>
<div id="sub-title">
#sub-title
<div id="sub-left">
#sub-left
</div>
<div id="sub-right">
#sub-right
</div>
</div>
</div>
</body>
</html>
#sub-left, #sub-right
{
display: inline-block;
}
Via Bootstrap Grid, you can easily get the cross browser compatible solution.
<div class="container">
<div class="row">
<div class="col-sm-6" style="background-color:lavender;">
Div1
</div>
<div class="col-sm-6" style="background-color:lavenderblush;">
Div2
</div>
</div>
</div>
jsfiddle: http://jsfiddle.net/DTcHh/4197/
You do it like this:
<table>
<tr>
<td colspan="2">TITLE</td>
</tr>
<tr>
<td>subleft</td><td>subright</td>
</tr>
</table>
EASY - took me 1 minute to type it.
Remember the CSS file needs to be downloaded to the client, so don't worry about the waffle about extra tags, its irrelavent in this instance.

Resources