中心图像并保持相同的高度

时间:2017-08-23 22:20:25

标签: html css image overflow

如何在不更改原始大小的情况下,仅在父div中使用css居中图像?

.main-img {
            display: block;
            width: 180px;
            overflow: hidden;
            align-self: flex-start;
        }
<div class="main-img">
  <img src="http://via.placeholder.com/300x50.png" width="1280px" height="550px" alt="main image" />
</div>

2 个答案:

答案 0 :(得分:0)

要将元素水平居中,您需要查找margin: 0 auto,因为<div>元素默认为 block-level (因此您不需要&# 39;实际上需要display: block):

&#13;
&#13;
.main-img {
  margin: 0 auto;
  width: 180px;
  overflow: hidden;
  align-self: flex-start;
}
&#13;
<div class="main-img">
  <img src="http://via.placeholder.com/300x50.png" width="1280px" height="550px" alt="main image" />
</div>
&#13;
&#13;
&#13;

使用display: flex,{{1 }和align-items: center属性值。请注意,您还需要指定justify-content: center属性:

&#13;
&#13;
height
&#13;
.main-img {
  height: 180px;
  border: 1px solid black;
  display: flex;
  align-items: center;
  justify-content: center;
}

.main-img img {
  width: 140px;
  height: 140px;
}
&#13;
&#13;
&#13;

希望这有帮助! :)

答案 1 :(得分:0)

<强> WAY1: 水平:

.main-img {
  height: 180px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.main-img img {
  width: 200px;
  height: 200px;
}

垂直:

.main-img {
  /* ... other code here such as width and height ... */
  position: relative;
}
.main-img img {
  position: relative; 
  left: 50%;
  transform: translateX(-50%);
}

<强> Way2: 水平:

.main-img {
  /* ... other code here such as width and height ... */
  position: relative;
}
.main-img img {
  position: relative; 
  top: 50%; 
  transform: translateY(-50%);
}

垂直:

.main-img {
  /* ... other code here such as width and height ... */
  position: relative;
}
.main-img img {
  position: relative; 
  top: 50%; 
  left: 50%;
  transform: translate(-50%, -50%);
}

纵向和横向:

function getpsas(id) {
    [ps, as] = Object.assign([ps, as], {
        [id]: [properties, attributes][id]
            .split(" ")
            .map(function (element) { var eqlpos = element.lastIndexOf("="); return { name: element.substr(0, eqlpos), type: element.substr(eqlpos + 1) }; })
            .filter(element => /^(vegetable|fruit)$/.test(element.type))
    });
}

var properties = "apple=fruit",
    attributes = "carrot=vegetable banana=fruit cherry=fruit fruit",
    ps = [],
    as = [];

getpsas(0);
getpsas(1);

console.log(ps);
console.log(as);