The Web Design Group

... Making the Web accessible to all.

Welcome Guest ( Log In | Register )

> Auto margin in CSS
Shervan
post Sep 1 2023, 10:34 AM
Post #1





Group: Members
Posts: 2
Joined: 5-August 23
Member No.: 29,003



Hello,

When I set margin-left: auto;, why the image push to the right-hand side?


CODE

<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" type="text/css" href="css/style.css" />
</head>

<body>
    <div class="imgClass">
<img src="images/flower.jfif"/>
</div>
</body>

</html>


CODE
.imgClass {
    display: block;
    width: 200px;
margin-left: auto;
}
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
 
Reply to this topicStart new topic
Replies
Christian J
post Sep 1 2023, 11:46 AM
Post #2


.
********

Group: WDG Moderators
Posts: 9,678
Joined: 10-August 06
Member No.: 7



It's the DIV, not the IMG. This is described in a very cryptic way at https://www.w3.org/TR/CSS22/visudet.html#Co...ths_and_margins where I believe 10.3.3 Block-level, non-replaced elements in normal flow applies to a DIV with specified width. From that section, is suppose this rule applies:

"If there is exactly one value specified as 'auto', its used value follows from the equality."


I assume "equality" means the width of the containing block (BODY in this case), minus 'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' (that are all zero in this case, except the width). unsure.gif

Since the unspecified margin-right defaults to its initial value (zero), I guess the left auto margin is allowed to fill up the entire width of the parent container (minus the DIVs own width), and as result the DIV is pushed to the right side.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
pandy
post Sep 1 2023, 06:48 PM
Post #3


🌟Computer says no🌟
********

Group: WDG Moderators
Posts: 20,735
Joined: 9-August 06
Member No.: 6



I wasn't aware of this behavior. I guess I've never tried it.


Shervan, what did you hope to accomplish? What is it you want to do?
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post Sep 1 2023, 07:57 PM
Post #4


.
********

Group: WDG Moderators
Posts: 9,678
Joined: 10-August 06
Member No.: 7



QUOTE(pandy @ Sep 2 2023, 01:48 AM) *

I wasn't aware of this behavior. I guess I've never tried it.

Maybe it's the same principle as centering content with both left and right auto margins:

CODE
div {
width: 200px;
margin-left: auto;
margin-right: auto;
background: lime;
}

but then the two margins will only get half of the "equality" each? unsure.gif
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post

Posts in this topic


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 



- Lo-Fi Version Time is now: 1st June 2024 - 12:45 AM