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

后端 未结 9 1386
迷失自我
迷失自我 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:37

    Use background-position:

    background-position: 50% 50%;
    
    0 讨论(0)
  • 2020-11-29 18:39

    This works for me :

    <style>
       .WidgetBody
            {   
                background: #F0F0F0;
                background-image:url('images/mini-loader.gif');
                background-position: 50% 50%;            
                background-repeat:no-repeat;            
            }
    </style>        
    
    0 讨论(0)
  • 2020-11-29 18:46

    For center or positioning the background image you should use background-position property . The background-position property sets the starting position of a background image from top and left sides of the element . The CSS Syntax is background-position : xvalue yvalue; .

    "xvalue" and "yvalue" supported values are length units like px and percentage and direction names like left, right and etc .

    The "xvalue" is the horizontal position of the background and starts from top of the element . It means if you use 50px it will be "50px" away from top of the elements . And "yvalue" is the vertical position that has the same condition .

    So if you use background-position: center; your background image will be centered .

    But I always use this code :

    .yourclass {
      background: url(image.png) no-repeat center /cover;
     }

    I know it is so confusing but it means :

    .yourclass {
      background-image: url(image.png);
      background-position: center;
      background-size: cover;
      background-repeat: no-repeat;
    }

    And I know that too the background-size is a new property and in the compressed code what is /cover but these codes means fill background sizing and positioning in windows desktop background .

    You can see more details about background-position in here and background-size in here .

    0 讨论(0)
提交回复
热议问题