这里主要还是由于没有对父控件即控件本身进行正确的定位。直接看代码, 首先对父控件需要使用相对布局,之后对子控件需要使用绝对布局,并且利用top,和bottom属性,结合margin: auto 0;,则可以达到效果。
.container-vertical { position: relative; width: 100%; height: 200px; background: deepskyblue; margin-bottom: 20px; } .container-vertical-item { position: absolute; width: 130px; height: 80px; text-align: center; background: yellow; line-height: 80px; top: 0; bottom: 0; margin: auto 0; }
.container-horization-vertical { position: relative; width: 100%; height: 200px; background: deepskyblue; margin-bottom: 20px; } .container-horization-vertical-item { position: absolute; width: 150px; height: 80px; background: yellow; line-height: 80px; text-align: center; top: 0; left: 0; bottom: 0; right: 0; margin: auto; }
小结: 这种方案在解决一些不算复杂的页面布局时还是很不错的,可以适配任何界面以及几乎所有的浏览器。但对于十分复杂的页面可能会需要其他的解决方案,但是从这个思路出发也可以得到启示。