这是我的代码,简单地说,我想让滑块居中。但图像没有显示,我非常确定位置[图像参考]是正确的。那我的代码有什么问题?帮我?
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
.slider {
width: 50%;
height: 30%;
margin: 0 auto;
}
.slider#img1 {
background: url('../images/all-images-sprite.png') no-repeat 0 -1368px;
background-size: cover;
width: 300px;
height: auto;
}
.slider#img2 {
background: url('../images/all-images-sprite.png') no-repeat 0 -1740px;
background-size: cover;
width: 300px;
height: auto;
}
.slider#img3 {
background: url('../images/all-images-sprite.png') no-repeat 0 -1568px;
width: 300px;
height: auto;
}
.slider#img4 {
background: url('../images/all-images-sprite.png') no-repeat 0 -967px;
width: 300px;
height: auto;
}
这是我的jsfiddle
答案 0 :(得分:1)
试试这个代码段
.sprite {
display: block;
}
.imgs {
width: 120px;
height: 76px;
background-repeat: no-repeat;
background-size: cover;
}
#img1 {
background-position: -5px -5px;
background-image: url(https://s32.postimg.org/ge685yjyt/all_images_sprite.png);
}
#img2 {
background-position: -5px -84px;
background-image: url(https://s32.postimg.org/ge685yjyt/all_images_sprite.png);
}
#img3 {
background-position: -5px -165px;
background-image: url(https://s32.postimg.org/ge685yjyt/all_images_sprite.png);
}
#img4 {
background-position: -5px -245px;
background-image: url(https://s32.postimg.org/ge685yjyt/all_images_sprite.png);
}

<div class="sprite">
<div id="img1" class="imgs"></div>
<div id="img2" class="imgs"></div>
<div id="img3" class="imgs"></div>
<div id="img4" class="imgs"></div>
</div>
&#13;
答案 1 :(得分:1)
保持尺寸宽度和高度所需的比例。
从你的小提琴我们可以从html(窗口的大小)开始。
您的错误:width:50%
然后是300px
。当容器为空时,height:auto
null 。
另外,要使用的选择器为.slider #id
,其中#id
是孩子
所以示例:) https://jsfiddle.net/rdjajvuh/3/
html,
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
.slider {
width: 50%;
height: 33vw;
margin: 0 auto;
border: solid;
}
/* demo test purpose*/
.slider>div {/* see me */
box-shadow:0 0 0 1px ;
}
.slider #img1 {
background: url('https://s32.postimg.org/ge685yjyt/all_images_sprite.png') no-repeat 0 0;
background-size: cover;
width: 100%;
height: 100%;
}
.slider #img2 {
background: url('https://s32.postimg.org/ge685yjyt/all_images_sprite.png') no-repeat 0 12%;/* % because size is 50%x33vw ... */
background-size: cover;
width: 100%;
height: 100%;
}
.slider #img3 {
background: url('https://s32.postimg.org/ge685yjyt/all_images_sprite.png') no-repeat 0 23%;
background-size: cover;
width: 100%;
height: 100%;
}
.slider #img4 {
background: url('https://s32.postimg.org/ge685yjyt/all_images_sprite.png') no-repeat 0 33.65%;
background-size: cover;
width: 100%;
height: 100%;
}
<div class="slider">
<div id="img1"></div>
<div id="img2"></div>
<div id="img3"></div>
<div id="img4"></div>
</div>
<a href="#">Previous</a>
<a href="#">Next</a>
对于背景位置,因为图像可以是任何大小,您可以使用%(在完整页面模式下运行代码段来查看原因)。根据您的需要调整它