如何在CSS之前显示半张图片?

时间:2018-08-14 10:21:02

标签: css

我使用选定的js插件来创建多个选择。 我正在尝试自定义其样式。我想要未选择项目时,左侧会有一个小的灰色正方形。如果选择该项目,它将显示一个蓝色小方块。 目前,我有一个包含2个小正方形的图像,我试图在左侧显示一个正方形,但它同时显示了两个正方形,我希望它仅显示上半部或下半部。 我怎样才能做到这一点? 骑这是我试图尝试的。

.chosen-container-multi.chosen-with-drop .chosen-drop .chosen-results li::before {
            content: url('https://image.ibb.co/iLpwap/Selection_Icon.png');
            position: relative; 
            padding-right: 10px;
 }

Display half a picture in before css

2 个答案:

答案 0 :(得分:1)

使用精灵表作为::before伪元素的内容,将无法按照您希望的方式进行裁剪。

相反,请使用精灵表作为背景图像,并适当调整伪元素的大小。

在选定状态下,重新放置背景图像,以便可见蓝色区域。

var config = {
   '.chosen-select': {},
   '.chosen-select-deselect': {
     allow_single_deselect: true
   },
   '.chosen-select-no-single': {
     disable_search_threshold: 10
   },
   '.chosen-select-no-results': {
     no_results_text: 'Oops, nothing found!'
   },
   '.chosen-select-rtl': {
     rtl: true
   },
   '.chosen-select-width': {
     width: '95%'
   }
 }
 for (var selector in config) {
   $(selector).chosen(config[selector]);
 }
.chosen-container-multi .chosen-choices li.search-choice {
   line-height: 30px !important;
   margin: 5px 5px 5px 0 !important;
 }

 .chosen-container-multi.chosen-with-drop .chosen-drop .chosen-results li::before {
   content: ""; /* Changed */
   position: relative;
   z-index: 100000;
   margin-right: 10px; /* Changed */
   display: inline-block; /* Added */
   width: 22px; /* Added */
   height: 24px; /* Added */
   background: url(https://image.ibb.co/iLpwap/Selection_Icon.png); /* Added */
 }

 .chosen-container-multi.chosen-with-drop .chosen-drop .chosen-results li.result-selected::before {
   background-position: 0 -24px; /* Added */
 }

 .chosen-container-multi .chosen-drop .result-selected {
   color: #444 !important;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css" rel="stylesheet"/>

<select chosen multiple data-placeholder="Select a item" class="chosen-select" style="width: 400px;">
    <option value="18">Item Test 1</option>
    <option value="19">Item Test 2</option>
    <option value="20">Item Test 3</option>
    <option value="" selected="selected">Select a Item</option>
</select>

答案 1 :(得分:0)

我已经更新了代码,您可以检查吗

http://jsfiddle.net/L6kmd3rb/14/

 .chosen-container-multi .chosen-choices li.search-choice {
line-height: 30px !important;
margin: 5px 5px 5px 0 !important;
}

.chosen-container-multi.chosen-with-drop .chosen-drop .chosen-results li::before {
content: url('https://image.ibb.co/iLpwap/Selection_Icon.png');
position: relative; /*or absolute*/
 z-index: 100000; /*a number that's more than the modal box*/
 padding-right: 10px;
 height:20px;
 display:block;
 overflow:hidden;
}
.chosen-container-multi .chosen-drop .result-selected {
color: #444 !important;
}

谢谢