Sorry for reviving an old thread. The reason for doing it is that I have been revisiting this problem, and been playing around a little. I'm posting this back here as a reference for myself, and maybe for others who are working on the same problem.
Short summary of the problem: to move a div (containing text) around on the screen, eg. center it or letting it float right or left.
Goal: being able to e.g. center a block of e.g. left-justified text
Example for illustration purposes:
Code:
<div class="outer">
<div class="inner">
<div class="all_left">This is the first line, which is a long one</div>
<div class="all_center">This second line is shorter</div>
<div class="all_right">This line is shortest</div>
</div>
<p class="margin_top">This is paragraph 1. It follows directly after the inner div and need to be cleared to take its rightful place in the document flow.</p>
</div>
<p>This is paragraph 2. It follows directly after the outer div. It should be unaffected by whatever is inside the outer div.</p>
CSS to discribe the classes used:
Code:
body{
background-color:green;
}
.all_right{
text-align:right !important;
}
.all_left{
text-align:left !important;
}
.all_center{
text-align:center !important;
}
.margin_top{
margin-top:2em;
}
p{
text-indent:1em !important;
margin-top:0;
margin-bottom:0;
text-align:justify;
}
I have found at least three ways of doing this:
1. Using float:
Code:
.outer{
width:100%;
background-color:blue;
}
.inner{
float:right;
background-color:red;
}
.inner + *{
/*Clearing whatever comes after the floating div*/
clear:both;
}
Pros: clean code, easy to read. The outer div is not necessary
Cons: the floating element needs to be cleared. Some CSS properties are ignored, e.g. the margin-top of the first paragraph. Text can only float left or right. Impossible to center the inner block.
2. Alignment of an inline-block
Code:
.outer{
width:100%;
background-color:blue;
text-align:right;
}
.inner{
background-color:red;
display:inline-block;
}
Pros: block can be aligned left, right or centered, depending on the text-align-property
Cons: inner and outer div needed, more messy code. Rendering machine needs to support display- and text-align-property
3. Adjusting margins of table
Code:
.outer{
width:100%;
background-color:blue;
}
.inner{
background-color:red;
display:table;
margin-left:auto;
margin-right:0;
}
Pros: Outer div not needed. Clean code. Inner block can be centered by setting both margin-left and margin-right to auto.
Cons: Rendering engine must support display-property.
Question: is the last "method" semantically correct? I.e, does display:table mean that I'm saying that the inner block
is a table (not semantically correct) or am I stating that is should just be
presented as if it were a table? I am guessing the last, and that it is "valid" semantically as well as technically.
Full example attached in zip-file