I suspect that the answer to this question is actually pretty straightforward and I’m just missing something obvious here but I can’t find the answer on W3 so I’m asking you guys.
Basically I’m trying to center an image beneath my logo and social media icons like this:
My strategy to do this was simple:
Float logo left.
Float social media icons right.
Clear: Both
Horizontal-Align: Center the image.
The only thing is, that didn’t work.
Currently, I am achieving the centered effect only in a makeshift fashion with the following HTML and CSS:
This method relies on me “eye-balling” a width that is “roughly centered” and also requires a margin-top to keep the thing below the logo and icons. I feel there should be a way to do this with Clear: Both but I just can’t hack it.
So, I was fiddling around with this project again and I got a solution that (to me at least) seems satisfactory.
What I did was ridiculously simple: I just wrapped a div around the IMG and then used {clear: both; margin: 0px auto;}
In hindsight it seems like a pretty easy solution, but it seems like adding piles and piles of divs like this is sort of cluttering up the style sheet.
Is there any reason why IMG doesn’t respond to clear:both the way a div does?
(I didn’t read the thread carefully, so this response addresses your last question in isolation.)
A div is a block object. Blocks respond to {margin:0 auto;} An image is an inline object. Inline objects can be centered by assigning {text-align:center} to their parent container (just like text is centered), OR by setting the img tag to {display:block;margin:0 auto;}.
You would need to give the div a width otherwise margin:auto wont work on the div because the div will be full width and there’s nothing to centre. Or alternatively apply text-align:center to the div and that will centre inline children such as images and text
Is there any reason why IMG doesn’t respond to clear:both the way a div does?
‘clear’ only applies to block elements and not inline elements (which images are by default). The solution is simply to set your image to display:block and then use margin:auto and clear:both as already mentioned above. No need for extra divs
Working example (just copy paste and view while online).