Florian.C Florian.C - 10 days ago 4
CSS Question

Place an icon at the right of a label with CSS



#accordion input {
display: none;
}
#accordion label {
background: #88C2E6;
color: white;
cursor: pointer;
display: block;
margin-bottom: .125em;
padding: .25em 1em;
z-index: 20;
min-height: 40px;
line-height: 40px;
}
#accordion label:hover {
opacity: 0.6;
}

#accordion label:after{
content:url(http://image.noelshack.com/fichiers/2016/48/1480523700-arrow-dl.png);
background-position: right;
}

#accordion input:checked + label {
background: #88C2E6;
color: white;
margin-bottom: 0;
}
#accordion article {
background: white;
height:0px;
overflow:hidden;
z-index:10;
}
#accordion article p {
padding: 1em;
}
#accordion input:checked article {
}
#accordion input:checked ~ article {
height: auto;
margin-bottom: .125em;
border-left: solid 1px #88C2E6;
border-right: solid 1px #88C2E6;
}

<div id="accordion">
<div>
<input type="checkbox" id="check-1" />
<label for="check-1">Some label</label>
<article>
<p>Some text</p>
</article>
</div>
</div>





I have an accordion which consists of an input with a label and an article, when I click the label, the article expands or retracts. I'd like to add an icon at the right end of the label.

I tried using :after, like this :

#accordion label:after{
content:url(/img.png);
}


But then, the icon is placed right after the text, like this


Text ICON


And I'd like it to be placed at the right, like this


Text----------------------------------------------------------------------ICON


When I use the property background-position, it remains at the same place.

How should I do this ?

Answer

One option you could go with is setting #accordion label's position to relative and the :after pseudo element to absolute. Then assign it with a right value of 0 (or whatever value you want).

#accordion input {
	display: none;
}
#accordion label {
	background: #88C2E6;
    color: white;
	cursor: pointer;
	display: block;
    position: relative;
	margin-bottom: .125em;
	padding: .25em 1em;
	z-index: 20;
    min-height: 40px;
    line-height: 40px;
}
#accordion label:hover {
	opacity: 0.6;
}

#accordion label:after{
    content:url(http://image.noelshack.com/fichiers/2016/48/1480523700-arrow-dl.png);
    position: absolute;
    right: 0;
}

#accordion input:checked + label {
	background: #88C2E6;
	color: white;
	margin-bottom: 0;
}
#accordion article {
	background: white;
	height:0px;
	overflow:hidden;
	z-index:10;
}
#accordion article p {
	padding: 1em;
}
#accordion input:checked article {
}
#accordion input:checked ~ article {
	height: auto;
	margin-bottom: .125em;
    border-left: solid 1px #88C2E6;
    border-right: solid 1px #88C2E6;
}
<div id="accordion">
    <div>
        <input type="checkbox" id="check-1" />
        <label for="check-1">Some label</label>
        <article>
            <p>Some text</p>
        </article>
    </div>
  </div>