tdoakiiii
tdoakiiii

Reputation: 372

Align a div vertically inside an inline-block

I have an unknown amount of divs that will be populated within an inline-block div. There's no problem when there is more than one div as it looks fine, but when there is only one div I want it to be centered in the parent. I want to try to do this without any fixed/absolute positioning and hopefully without using javascript.

In the fiddle you can see the first column, the div with "Put me in the middle" should be in the middle.

http://jsfiddle.net/Lzzyywf2/5/

<div class="inlineb">
    <div class="insideInline">Hello</div>
</div>
<div class="inlineb">
    <div class="insideInline">Hello</div>
    <div class="insideInline">Hello</div>
</div>

.inlineb {
    min-height:102px;
    display:inline-block;
    border:1px red solid;
    vertical-align:top;
}
.insideInline {
    height:50px;
    border:1px solid blue;
}

Upvotes: 1

Views: 70

Answers (3)

Josh Harrison
Josh Harrison

Reputation: 6004

If you are able to manually add a class for those containers with only one child, this would work:

http://jsfiddle.net/Lzzyywf2/6/

<div class="inlineb one-child">
    <div class="insideInline">Hello</div>
</div>

combined with:

.one-child:before {
    content: "";
    display: block;
    height: 25px;
}

If you can't add a class, this will work in IE9+:

http://jsfiddle.net/Lzzyywf2/9/

.insideInline:only-child {
    display:block;
    margin-top:25px;
}

Credit to the OP for improving on this idea!

Upvotes: 1

ChrisJ
ChrisJ

Reputation: 225

Flex box will make your life easier:

.flex-contain{
  padding: 0;
  margin: 0;
  list-style: none;
  -ms-box-orient: horizontal;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -moz-flex;
  display: -webkit-flex;
  display: flex;
  width:900px;
  height:500px;
  background:#000;
  align-items:center;
  align-content:center;
  }

  .flex-item {
    height:200px;
    width:200px;
    background:yellow;
    margin:0 auto;
  }

http://codepen.io/cjthedizzy/pen/vEpyvR

Upvotes: 0

alexwc_
alexwc_

Reputation: 1603

Try :only-child for .insideInline. This will target the element if there is only one inside the parent. Here's my fiddle.

#wrapper {
}
.inlineb {
    min-height:102px;
    display:block;
    border:1px red solid;
    vertical-align:top;
    width:126px; /*or whatever value*/
}
.insideInline {
    height:50px;
    border:1px solid blue;
    display:inline-block;
    width:37px;/*or whatever value*/
}

.inlineb .insideInline:only-child {
    display:block;
    margin:0 auto;
}

Upvotes: 1

Related Questions