简体   繁体   中英

float of the background-image

I have the <div> with background-image css rule.
Html

<div class="myclass">Hello world</div>

CSS

.myclass
{
    background-image: url('http://www.europe-trip.cz/icons/spinner.gif');
    background-repeat: no-repeat;
    background-position:left;
    border: 1px red dotted;
}    

JSFiddle DEMO

How can I make background-image inside div to float the text?

PS:I cann't create another div (or another element) inside the currrent div

Add padding to the div to shift the text.

.myclass
{
    background-image: url('http://www.europe-trip.cz/icons/spinner.gif');
    background-repeat: no-repeat;
    background-position:left;
    border: 1px red dotted;
    padding-left: 20px;
}

JS Fiddle: http://jsfiddle.net/zqeTx/1/

You can use the ::before pseudo element .

jsfiddle Demo

.myclass:before
{
    background-image: url('http://www.europe-trip.cz/icons/spinner.gif');
    background-repeat: no-repeat;
    background-position:left;
    content: "";
    display: inline-block;
    width: 16px;
    height: 16px;
}

The advantage of this method is that if there's a long text with multiple lines it will indent the text only on the first line.

Multiple lines jsFiddle Demo

Add text-indent css property and also pin the background image to top so that if the text goes to second line, the background will not move.

.myclass {
    background-image: url('http://www.europe-trip.cz/icons/spinner.gif');
    background-repeat: no-repeat;
    background-position:2px 2px;
    border: 1px red dotted;
    text-indent:20px;
}

Working Fiddle

Use This CSS DEMO HERE

.myclass
{   
    border: 1px red dotted;
}
.myclass:before
{
    background-image: url('http://www.europe-trip.cz/icons/spinner.gif');
    background-repeat: no-repeat;
    background-position:left;
    padding-left:20px;
    content:'';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM