skip to Main Content

It’s my first post here. I need to center my background image horizontally and vertically in CSS,however whatever way I try the image stubbornly remains on its place. I’ve read like 30 posts on the issue, but nothing seems to work for me. Thank you for any suggestions

.angryjalapeno {
    width: 500px;
    height: 300px;
    background-image: url(https://placehold.co/200x200);
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
    display: flex;
    justify-content: center;
    align-items: center;
}
<div class="angryjalapeno"></div>

HTML version here

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Background as color and image</title>
    <link rel="stylesheet" href="css/style.css">

        <div class="angryjalapeno">


        </div>
</head>
<body>
</body>
</html>

3

Answers


  1. I recommend that you change your background-position property to something like this.

    background-position: center center;
    
    Login or Signup to reply.
  2. If your picture is bigger than 300×500, then your code true. But if it’s smaller than this size you need to remove background-size: cover;

    Login or Signup to reply.
  3. Removing background-size: cover puts the image placeholder in the center of the div.

    .angryjalapeno {
        width: 500px;
        height: 300px;
        background-image: url(https://placehold.co/200x100);
        background-repeat: no-repeat;
        background-position: center;
        /* background-size: cover; */
        display: flex;
        justify-content: center;
        align-items: center;
    }
    <div class="angryjalapeno">
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search