Auto margin in CSS |
Auto margin in CSS |
Shervan |
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; } |
Christian J |
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). 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. |
pandy |
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? |
Christian J |
Sep 1 2023, 07:57 PM
Post
#4
|
. Group: WDG Moderators Posts: 9,678 Joined: 10-August 06 Member No.: 7 |
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? |
pandy |
Sep 2 2023, 12:02 PM
Post
#5
|
🌟Computer says no🌟 Group: WDG Moderators Posts: 20,735 Joined: 9-August 06 Member No.: 6 |
Don't know. Never understood the theory behind that either, just learnt how it it works. Maybe it should have been called margin: max. Because that seems to be how it works, take everything that's available.
|
Lo-Fi Version | Time is now: 31st May 2024 - 10:41 PM |