Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: May I right-align an element by margin: 0 0 0 auto?

May I right-align an element by setting margin-left

margin: 0 0 0 auto;

but not float

float: right;

?

I don't know if this is right but it works, both in Chrome and Safari.

========

A.K's answer is what I need;

And this is also helpful, via Praveen Kumar: You can, but the support is limited. It works only in Chrome and Safari. Not even in Firefox, I guess. See, if you are going to target only Chrome browser, yes, you can. All the -webkit- based browsers support this, but not others. Choice is yours. :)

like image 382
Mr. Míng Avatar asked Sep 03 '12 05:09

Mr. Míng


2 Answers

Yes, you can right-align an element by setting margin-left:auto

But see the difference between margin and float results below:

Margin

The margin CSS property sets the margin for all four sides. It is a shorthand to avoid setting each side separately with the other margin properties: margin-top, margin-right, margin-bottom and margin-left.

Float:

The float CSS property specifies that an element should be taken from the normal flow and placed along the left or right side of its container, where text and inline elements will wrap around it.

SEE RESULT

like image 196
Ahsan Khurshid Avatar answered Sep 19 '22 12:09

Ahsan Khurshid


Solution 1: Using Positioning

You can make it using positioning if not by floating. Have the parent element as position: relative; and the element as position: absolute; with left: auto; and others as 0.

CSS

.parent {position: relative;}
.parent .child {position: absolute; left: auto; right: 0; width: 150px; height: 50px;}​​​

HTML

<div class="parent">
    <div class="child">
        Content
    </div>
</div>​

Fiddle: http://jsfiddle.net/U3JXk/
Fiddle: http://jsfiddle.net/U3JXk/1/ (With Border)

Solution 2: Resetting Display Attributes

If you are not willing to use positioning, you can try changing the display attributes of the element to appear as inline and use text-align as right.

CSS

.parent {text-align: right;}
.parent .child {display: inline;}
/* OR */
.parent .child {display: inline-block; *display: inline; *zoom: 1;}

HTML

<div class="parent">
    <div class="child">
        Content
    </div>
</div>

Fiddle: http://jsfiddle.net/U3JXk/2/
Fiddle: http://jsfiddle.net/U3JXk/3/ (With Border)

like image 21
Praveen Kumar Purushothaman Avatar answered Sep 21 '22 12:09

Praveen Kumar Purushothaman