Css垂直对齐与嵌套div [英] Css vertical alignment with nested divs

查看:220
本文介绍了Css垂直对齐与嵌套div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题是由于此相关问题的修复建议而产生的。



我有3个嵌套的div:outer,inner和item。

  ; div class =outer> 
< div class =inner>< div class =item>< / div>< / div>
< / div>

给定以下基本CSS:

  .outer {
width:50%;
height:100px;
border:1px solid red;
position:relative;
overflow-x:hidden;
box-sizing:border-box;
}
.inner {
border:1px solid blue;
height:100%;
position:absolute;
box-sizing:border-box;
line-height:98px;
}
.item {
width:100px;
height:94px;
background-color:yellow;
display:inline-block;
border:1px solid green;
box-sizing:border-box;
vertical-align:middle;挑战是使'item'div垂直居中,等于(或者没有)中间的itemdiv。b>

)间隙高于/低于,并且没有垂直滚动条出现。



这里的Codepen



更新:



正如下面指出的,我应该补充说,不同高度的多个项目必须居中。到目前为止,最好的答案是为每个项目添加一个负边距,导致以下结果: http:// codepen .io / anon / pen / dYWEYZ



但是,这个臭味很糟糕,因为它需要一个依赖于其他3个属性的偏移。 p>

解决方案

简单的解决方案是 http://codepen.io/anon/pen/jbmRjo



将此添加到您的.item类中:

  margin-top:-5px; 

这是因为你的外部和内部类的边框,以及内部类。如果你使边框2px而不是1px,那么边距顶部变为-9px。如果你将边界设置为1px,并将行高设置为96px,则页边距顶部变为-3px。



那么,为什么不能使用负的上限?


This question resulted from a fix suggested to this related question

I have 3 nested divs: outer, inner and item.

<div class="outer">
  <div class="inner"><div class="item"></div></div>
</div>

Given the following basic CSS:

.outer{
  width:50%;
  height:100px;
  border: 1px solid red;
  position:relative;
  overflow-x:hidden;
  box-sizing:border-box;
}
.inner{
  border:1px solid blue;
  height:100%;
  position: absolute;
  box-sizing: border-box;
  line-height:98px;
}
.item{
  width:100px;
  height:94px;
  background-color:yellow;
  display: inline-block;
  border:1px solid green;
  box-sizing:border-box;
  vertical-align:middle;
}

The challenge is to center the 'item' div vertically with equal (or no) gaps above/below, and no vertical scrollbars appearing.

Codepen here

Update:

As pointed out below, I should add that multiple items of different heights must be centered. The best answer so far is to add a negative margin to each item, resulting in the following: http://codepen.io/anon/pen/dYWEYZ

However, this smells bad (to me) as it requires an offset that depends on 3 other properties.

解决方案

The simple solution is http://codepen.io/anon/pen/jbmRjo

to add this to your .item class:

margin-top: -5px;

It's because of the borders on your outer and inner classes, as well as the line-height of the inner class. If you make the borders 2px instead of 1px, then the margin top becomes -9px. If you leave borders at 1px and make the line-height 96px the margin top becomes -3px.

So why can't you use a negative margin top?

这篇关于Css垂直对齐与嵌套div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆