【问题标题】:Base percentage off height instead of width in css? [duplicate]CSS中高度而不是宽度的基本百分比? [复制]
【发布时间】:2018-07-25 14:23:08
【问题描述】:
我在页面中有以下 css 以始终使我的图片居中:
img {
padding: calc(49% - 306px);
}
我遇到的问题是“49%”是基于页面宽度,而不是我想要的高度。有什么办法可以改变吗?谢谢!
注意:我的图片位于<div align="center"> 中以使其水平居中
【问题讨论】:
标签:
html
css
vertical-alignment
【解决方案1】:
你能用flexbox吗?
html, body, div.center {margin: 0;height: 100%;}
div.center {display:flex; align-items: center;}
img {
flex: 0 0 auto;
margin: auto;
}
<div class="center">
<img src="//placehold.it/306x100" alt="">
</div>
演示:http://output.jsbin.com/xotupegove
【解决方案2】:
如果没有你想要做的事情的完整背景,我猜 CSS Flex 是你最好的选择。我附上的 sn-p 向您展示了一种在图像不是全尺寸背景时在 div 内居中图像的方法。
请记住,此解决方案需要针对您的应用程序进行一些修改。
.container {
border:1px solid red;
margin:0 auto;
display:flex;
height:500px;
width:500px;
justify-content:center;
align-items:center;
}
<div class="container">
<img src="https://www.w3schools.com/howto/img_fjords.jpg" width="100px" height="100px">
</div>
【解决方案3】:
您可以将 img 元素更改为 div 并将图像作为背景图像,如下所示:
div {
width:100%;
height:100%;
background:url(logo.png) center center no-repeat;
}