FakeName123
FakeName123

Reputation: 147

Centering a div that contains images whose size is relative to the page width

I've tried the solutions in other threads, but I'm at a loss. I'd like two images, side by side, each one's width equal to 40% of the page width, and with 20px of margin between them, and the whole wazoo should be centered. Diagrammed approximately:

|            [img1 width:40%] 20px space [img2 width:40%]            |

I've gotten very close, but nothing quite works. Here's the closest I've gotten:

<!-- Starts centering with the addition of "width" to the div's style. -->
<div style="margin: 0 auto;">
    <img width=40% src="http://bit.ly/1mlbOp6" style="display: inline-block;">
    <img width=40% src="http://bit.ly/1mlbOp6" style="display: inline-block; margin-left: 20px;">
</div>

This code on JSFiddle: http://jsfiddle.net/98Se3/

It resolutely refuses to center without that div having a specified width. However, the width of the div can neither be set relative to the page width, or exactly in pixels, because it should be 40% + 20px + 40%. What am I missing?

Upvotes: 0

Views: 51

Answers (4)

Reinder Wit
Reinder Wit

Reputation: 6615

Just use text-align:center for the parent div:

<div style="text-align:center">
    <img width="40%" src="http://bit.ly/1mlbOp6">
    <img width="40%" src="http://bit.ly/1mlbOp6" style="margin-left: 20px;">
</div>

Check out this working fiddle

Upvotes: 2

Suresh Ponnukalai
Suresh Ponnukalai

Reputation: 13988

Use text-align:center; instead margin:0 auto;

<div style="text-align:center;">

DEMO

Upvotes: 1

Dirk En Carol Rennen
Dirk En Carol Rennen

Reputation: 33

<div style="text-align:center">...</div>

This way the content is centered, the div uses full width but unless it needs to be visible (border, background-color, ...) it does not visually matter. That last part may be solved by setting a <span> around the images and style that.

Upvotes: 1

Sarbbottam
Sarbbottam

Reputation: 5570

Are you looking for something like this fiddle

<!-- Starts working (approximately) with the addition of "width" to the div's style. -->
<div style="margin: 0 auto; width:100%">
    <img width=40% src="http://bit.ly/1mlbOp6" style="display: inline-block;"><img width=40% src="http://bit.ly/1mlbOp6" style="display: inline-block; margin-left: 20%;">
</div>

Updated margin-left: 20%; instead of margin-left: 20px;

And there is no gap between <img ...><img ..>

Upvotes: 1

Related Questions