Search code examples
htmlcssflexbox

Flexbox not working for image's background


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>

Solution

  • 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>