How to center a (background) image within a div?

2019-01-10 05:01发布

Is it possible to center a background image in a div? I have tried just about everything - but no success:

<div id="doit">
  Lorem Ipsum ...
</div>

//CSS
#doit { background-image: url(images/pic.png); background-repeat: none; text-align: center; }

Is this possible?

8条回答
forever°为你锁心
2楼-- · 2019-01-10 05:24
#doit {
    background: url(url) no-repeat center;
}
查看更多
甜甜的少女心
3楼-- · 2019-01-10 05:40

If your background image is a vertically aligned sprite sheet, you can horizontally center each sprite like this:

#doit {
    background-image: url('images/pic.png'); 
    background-repeat: none;
    background-position: 50% [y position of sprite];
}

If your background image is a horizontally aligned sprite sheet, you can vertically center each sprite like this:

#doit {
    background-image: url('images/pic.png'); 
    background-repeat: none;
    background-position: [x position of sprite] 50%;
}

If your sprite sheet is compact, or you are not trying to center your background image in one of the aforementioned scenarios, these solutions do not apply.

查看更多
我命由我不由天
4楼-- · 2019-01-10 05:41

This works for me :

<style>
   .WidgetBody
        {   
            background: #F0F0F0;
            background-image:url('images/mini-loader.gif');
            background-position: 50% 50%;            
            background-repeat:no-repeat;            
        }
</style>        
查看更多
仙女界的扛把子
5楼-- · 2019-01-10 05:43

This works for me:

.network-connections-icon {
  background-image: url(url);
  background-size: 100%;
  width: 56px;
  height: 56px;
  margin: 0 auto;
}
查看更多
小情绪 Triste *
6楼-- · 2019-01-10 05:45

try background-position:center;

EDIT: since this question is getting lots of views, its worth adding some extra info:

text-align: center will not work because the background image is not part of the document and is therefore not part of the flow.

background-position:center is shorthand for background-position: center center; (background-position: horizontal vertical);

查看更多
干净又极端
7楼-- · 2019-01-10 05:47

Use background-position:

background-position: 50% 50%;
查看更多
登录 后发表回答