简体   繁体   English

在内联块内垂直对齐div

[英]Align a div vertically inside an inline-block

I have an unknown amount of divs that will be populated within an inline-block div. 我有一个未知数量的div,它将填充在一个内联块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. 看起来不错时,有一个以上的div没问题,但是当我只有一个div时,我希望它位于父级的中心。 I want to try to do this without any fixed/absolute positioning and hopefully without using javascript. 我想尝试在没有任何固定/绝对定位的情况下尝试执行此操作,希望不使用JavaScript。

In the fiddle you can see the first column, the div with "Put me in the middle" should be in the middle. 在小提琴中,您可以看到第一列,带有“将我放在中间”的div应该在中间。

http://jsfiddle.net/Lzzyywf2/5/ 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;
}

If you are able to manually add a class for those containers with only one child, this would work: 如果您能够为只有一个孩子的那些容器手动添加一个类,则可以这样做:

http://jsfiddle.net/Lzzyywf2/6/ 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+: 如果您无法添加课程,则可以在IE9 +中使用:

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

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

Credit to the OP for improving on this idea! 感谢OP改进这个想法!

Try :only-child for .insideInline . 对于.insideInline尝试:only-child 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;
}

Flex box will make your life easier: Flex盒子会让您的生活更轻松:

.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 http://codepen.io/cjthedizzy/pen/vEpyvR

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM