Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right-align block elements in HTML

Tags:

html

css

I'd like to right-align block elements in a floating container.

Assume the following markup.

<div style="float: left;">
  <img style="display: block;" src="...">
  <img style="display: block;" src="...">
</div>
   current                 wanted
+-----------+          +-----------+
|+-------+  |          |  +-------+|
||       |  |          |  |       ||
||       |  |          |  |       ||
|+-------+  |   --->   |  +-------+|
|+----+     |          |     +----+|
||    |     |          |     |    ||
|+----+     |          |     +----+|
+-----------+          +-----------+

What I've tried:

  • div { text-align: right; } - works in IE8, fails in Firefox (naturally, the images are blocks and not supposed to be affected by text-align)
  • img { margin: 0 0 0 auto; } - works in Firefox, fails in IE8
  • floating the images to the right - does not work as I never want the images on the same line. Also, floated images no longer push down the following content.

What else can I try? I prefer a pure CSS solution, if that's at all possible.


UPDATE

Here's a fiddle that explains the full markup: http://jsfiddle.net/Tomalak/yCTHX/3/

Setting float: right; works for all real browsers, for IE8 it extends the image box in the row first over the entire width and pushes down the box with the text.

like image 827
Tomalak Avatar asked Jul 12 '13 12:07

Tomalak


People also ask

How do you align a block element?

Center Align Elements To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.

How do I move a block to the right CSS?

Fixed Positioning Move Left - Use a negative value for left. Move Right - Use a positive value for left. Move Up - Use a negative value for top. Move Down - Use a positive value for top.

How do I align a div to the right side?

Use CSS property to set the height and width of div and use display property to place div in side-by-side format. float:left; This property is used for those elements(div) that will float on left side. float:right; This property is used for those elements(div) that will float on right side.


2 Answers

div > img { float:right; clear:right; }
like image 159
Silviu-Marian Avatar answered Oct 23 '22 20:10

Silviu-Marian


The correct way to align an element with CSS is to set text-align on the container and margin on the children elements.
Your tries are wrong since you are setting margin and text-align on the img tag. Your css should look like:

div {
float:right;
text-align: right;
}
img {
margin: 0 0 0 auto;
}  

Just tested on ie8, ff and chrome.
http://jsfiddle.net/notme/wfwjf/2/

like image 5
pasine Avatar answered Oct 23 '22 21:10

pasine