需求点
固定定位div中添加图片内容,保证图片垂直居中,并且自适应。
一般在第三方UI组件中,这种布局需求较为常见
解决方案一 (亲测有效)
HTML代码:
<div class="el-carousel__item is-active is-animating"><img src="/static/img/login-bg3.51c5580.png" alt="">
</div>
CSS代码:
.el-carousel__item {position: absolute;width: 100%;height: 100%;top: 0;left: 0;display: inline-block;overflow: hidden;z-index: 0;
}
/* 这是图片正常居中的常规写法 */
img {position: absolute;top: 50%;left: 50%;-webkit-transform: translate(-50%, -50%);transform: translate(-50%, -50%);width: 81.7%;
}
img的样式中,它的宽度由设计稿的定宽与图片宽度的比例决定的。
- 温馨提示:
- 宽度撑不开问题:可以在img的外层div 添加
width:100%; padding: 0 50%
解决撑不开父类div的问题。 - 高度占不满屏幕问题:保证当前div的高度是从最外层div的高度一层一层继承下来,如果没有,就需要在其父级添加
height: 100%
或者height: inherit
。