DanCoder
DanCoder

Reputation: 23

Vertical alignment of a DIV inside another DIV

I'm trying for some days to vertically align the .sl_container.
I have tried vertical-align: middle, but that doesn't work.

If i specify a height and width for the .slideshow, then using top: 50%; and transform: translateY(-50%);, that works. See here.
The problem is that if i remove the height and width for the slider to take up the available space and adapt, then the this will make the inner div appear moved upwards. See here.

display: table-cell; was not an option as it would have the arrows at the sides of the full width of the parent div instead of on the image.

I've tried flex before, and it gets vertically aligned, but if the parent DIV width is bigger than the child DIV, for some reason it goes to

As I said, I’ve tried multiple ways and there is not a single one that gets it done well without breaking the arrow positions.

What I’ve done until now: JSFiddle
The before mentioned settings are commented out in the CSS section.

Any insight to this would be helpful as to a way or how to get it aligned without breaking the whole slide and arrows.


FYI: There is a bleeding effect from the DIV's or images expanding like 1-2px to the bottom, reason why I have each DIV coloured to see if I can fix it. I'm sure it something silly and if you know what it is, please say so. It’s not important so I don’t really care much. xD

Upvotes: 1

Views: 5748

Answers (3)

Hujaakbar
Hujaakbar

Reputation: 1082

You can use Flexbox or Grid to vertically align elements of a container. But if you don't want to use flexbox or grid and you only need vertical-alignment, you can use align-content property. It works not only in Flexbox, and Grid but also block-level elements as well. mdn link

The CSS align-content property sets the distribution of space between and around content items along a flexbox's cross axis, or a grid or block-level element's block axis.

So, you can center elements of a block-level container with one line of code:

.slideshow {
   border: 3px solid black;
   height: 400px;

   align-content: center;
}

.slides{
  height: 100px;
  background: orange;
  text-align:center;
}
<div class='slideshow'>
  <div class='slides'>
   slides
  </div>
</div>

Upvotes: 0

krmzv
krmzv

Reputation: 387

Try using flexbox, it's the most elegant solution for vertical alignment

E.g.

<div class='parentDiv'>
  <div class='childDiv'>
  </div>
</div>

.parentDiv {
   display: flex;
   align-items: center;
   justify-content: center;
}

Take a look -> here

Upvotes: 3

Scott Brown
Scott Brown

Reputation: 334

Add this to your slideshow element, using flexbox. Flex Needs prefixing for IE11 (caniuse)

.slideshow {
    display: flex;
    align-items: center;
}

Edit: I enabled the commented height and width styles in your jsFiddle, but this method will vertically align slideshow child regardless of width and height.

Upvotes: 5

Related Questions