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

后端 未结 9 1384
迷失自我
迷失自我 2020-11-29 17:57

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

Lorem Ipsum ...
相关标签:
9条回答
  • 2020-11-29 18:24

    This works for me:

    .network-connections-icon {
      background-image: url(url);
      background-size: 100%;
      width: 56px;
      height: 56px;
      margin: 0 auto;
    }
    
    0 讨论(0)
  • 2020-11-29 18:28

    This works for me for aligning the image to center of div.

    .yourclass {
      background-image: url(image.png);
      background-position: center;
      background-size: cover;
      background-repeat: no-repeat;
    }
    
    0 讨论(0)
  • 2020-11-29 18:32

    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);

    0 讨论(0)
  • 2020-11-29 18:34

    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.

    0 讨论(0)
  • 2020-11-29 18:36
    #doit {
        background: url(url) no-repeat center;
    }
    
    0 讨论(0)
  • 2020-11-29 18:36

    This works for me:

    #doit{
        background-image: url('images/pic.png');
        background-repeat: no-repeat;
        background-position: center;  
    }  
    
    0 讨论(0)
提交回复
热议问题