[英]Create Fluid Background Image with CSS
我正在尝试构建一个可以根据屏幕尺寸调整大小的简单流体图像。
但是当浏览器的宽度变小时,我很难使图像变小。
HTML:
<main>
<section class="slider-ctn">
<figure class="logo"></figure>
</section>
</main>
CSS:
.slider-ctn figure.logo {
margin: auto;
background-image: url('../Images/logo.200x100.png');
width: 200px;
height: 100px;
}
如果你设置background-size
,以100% 100%
或cover
图像将延伸到适合的容器。 删除宽度(或通过设置父级的宽度限制宽度)并设置height: 0; padding-top: 50%
height: 0; padding-top: 50%
在图形上height: 0; padding-top: 50%
,以使图形的高度为宽度的一半,因此长宽比将与图像匹配并且流畅。
* {margin:0;padding:0;} .slider-ctn { margin: auto; width: 200px; } .slider-ctn figure.logo { background: url('https://dummyimage.com/200x100/000/fff') top left no-repeat; height: 0; background-size: cover; padding-top: 50%; }
<main> <section class="slider-ctn"> <figure class="logo"></figure> </section> </main>
只需使用以下代码将以下内容添加到您的head
标签中:
<meta name="viewport" content="width=device-width, initial-scale=1">
您应该将contain
作为背景大小添加到CSS:
.slider-ctn figure.logo {
margin: auto;
background-image: url('../Images/logo.200x100.png');
background-position:center center;
background-repeat:no-repeat;
background-size:contain;
width: 200px;
max-width:100%;
height: 100px;
display:inline-block;
}
使用背景图像时,请不要忘记每次在背景属性中添加position
并repeat
。
另外,如果它小于徽标容器,我还添加了max-width
以适合父容器。
注意:请勿使用背景尺寸的
cover
,因为这样会切掉徽标,使其仅适合width
限制,contain
将适合width
和height
。
使用大众单位和包含的另一种选择。
如果知道图像的纵横比,则可以使用vw(视图宽度)作为宽度和高度的单位。
我正在使用长宽比为4x3的图像。 如果我希望宽度始终是屏幕的80%,我将使用80vw。 然后,我的身高将是宽度的3/4,即60vw。
然后,请确保使用contain作为背景大小。
试试这个CSS,看看它是否满足您的需求:
.slider-ctn figure.logo { margin: auto; background-image: url('https://i.ytimg.com/vi/tntOCGkgt98/maxresdefault.jpg'); background-size: contain; background-repeat: no-repeat; width: 80vw; height: 60vw; border: 5px solid red; }
我认为将图像的最大宽度设置为100%应该可以解决问题。
.slider-ctn figure.logo {
background-image: url('../Images/logo.200x100.png');
background-repeat:no-repeat;
background-size:contain;
background-position:center;
width: 200px;
height: 100px;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.