Margin using adjacent selector in css

I am trying to display multiple images in an absolutely positioned div. The div has the text alignment set to the center, which puts the images in the center nicely. Then I added a margin-left rule with an adjacent roller selector for the images to give them some space, but not spoil all the centering goodness.

Images are static inline-block elements by default.

.mydiv img + img
{
    margin-left:20px;
}

      

This gives my images a little space between eachother. However, when images are stacked on top of another, when they overflow the div, the margin still applies so that the image below is not vertically aligned. I think this is because they are still siblings, they are only visually separated.

Is there any other way to achieve this with CSS? My div is fluid, so I really don't want to use fixed margins entirely.

Here is a sample image: http://i54.tinypic.com/w8aogp.png

As you can see, the second row of images and below is offset along the edge I want between the images. I would like them to be vertically aligned, of course. If I could somehow use a selector for something like "img preceded by implicit newline" and remove the field?

Ignore the "top" edge - this will be a fixed number, regardless of whether the image is directly next to the white div or not. However, I want a zero left margin whenever the img is directly adjacent (visually) to the container div.

+2


source to share


1 answer


If your parent div is variable width and your images stay floating, I think the only way to make sure your images are equally spaced is to declare margin: 10px

(from all sides), or at least left and right. This way, no matter how many images you have in a line, they will always be correctly aligned.

On the other hand, if the parent div

is of a fixed width and you know exactly how many images are in each line, you can insert an empty div

each X-image, which will make your current selector work as desired, or you can create a new separator class, say .sep

for which you would declare margin-left: 20px;

and assign it to everyone but the first image in the line.



Other than that, I don't think there are any other pure CSS solutions.

+1


source







All Articles