zoukankan      html  css  js  c++  java
  • 截图图片两边使图片在盒子里居中的三种方法

    最近项目改版,需要在一个正方形的盒子区域中显示图片,由于旧数据中都是横向长方形的图片,旧数据又不能舍弃,产品就要求对于这种图片进行两边截取,在正方形盒子中只显示图片中间部分的(蛋)要(疼)求。

    经过一番尝试一共找到3种可以成功实现的方法,在此分享一下。

    原图如下fbd9162fea.jpg
    结果如下
    图片描述

    1.使用绝对定位+transform

    这个方法已经被广泛用来使指定元素在盒子中上下左右居中了,同样也适合上述场景

    <style>
    .img-box1 {
         200px;
        height: 200px;
        position: relative;
        overflow: hidden;
    }
    .img-box1 img {
        height: 200px;
        position: absolute;
        left: 50%;
        transform: translate(-50%,0);
    }
    </style>

    2.使用display:flex属性。

    不得不说flex非常强大,设置了display:flex以后,可以通过简单设置justify-content以及align-items来规定内部元素的呈现方式而不用做任何的计算。

    <style>
    .img-box2 {
         200px;
        height: 200px;
        overflow: hidden;
        display: flex;
        display: -webkit-flex; /* Safari */
        justify-content: center;
        -webkit-justify-content: center; /* Safari 6.1+ */
        align-items: center;
        border: solid 1px black;
    }
    .img-box2 img {
        height: 200px;
    }
    </style>

    3.大比例负margin

    不得不说最后一种方法略微诡异,一般margin:0 -100%;即可,但在实际使用过程用发现有时会失效,怀疑和图片、盒子还有屏幕宽度之间的比例有关系,所以设成了-300%,设成-300%以后目前一切正常。

    <style>
    .img-box3 {
         200px;
        height: 200px;
        overflow: hidden;
        text-align: center;
    }
    .img-box3 img {
        height: 200px;
        margin: 0 -300%;
    }
    </style>

    html部分如下

    我用的是绝对定位+transform
    <div class="img-box1">
        <img src="http://pic.sucaibar.com/pic/201311/03/fbd9162fea.jpg" />
    </div>
    我用的是flex
    <div class="img-box2">
        <img src="http://pic.sucaibar.com/pic/201311/03/fbd9162fea.jpg" />
    </div>
    我用的是左右大比例负margin
    <div class="img-box3">
        <img src="http://pic.sucaibar.com/pic/201311/03/fbd9162fea.jpg" />
    </div>

    以上就是截取(隐藏)图片两侧让图片在盒子居中的3种方法了,希望能能对大家有用。

  • 相关阅读:
    Non-Photorealistic Rendering using OpenCV ( Python, C++ )
    Tensorflow Eager execution and interface
    Linear and Logistic Regression in TensorFlow
    TensorFlow Ops
    Introduction to TensorFlow
    Java Syntax Specification
    java方法的虚分派和方法表
    λ演算
    活性变量分析
    java垃圾回收机制
  • 原文地址:https://www.cnblogs.com/10manongit/p/12221462.html
Copyright © 2011-2022 走看看