如何在不更改原始大小的情况下,仅在父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>
答案 0 :(得分:0)
要将元素水平居中,您需要查找margin: 0 auto
,因为<div>
元素默认为 block-level (因此您不需要&# 39;实际上需要display: block
):
.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;
使用
display: flex
,{{1 }和align-items: center
属性值。请注意,您还需要指定justify-content: center
属性:
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;
希望这有帮助! :)
答案 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);