Search code examples
htmlcsspositionwidth

Why is one object bigger than the other (overlaps out of the sides) - CSS?


I'm trying to create a header with an image, fade over it and a title & sub-title. I created a new div for the fade box (& a separate div for the h1 & h2 so it could be at the bottom of the image). But somehow the fade container is wider than the image and I don't know how to make them the same size! I'd be very grateful for any help. I'm very new to all this!

https://i.sstatic.net/LZhLn.png

HTML:

<body>
<header>
    <img src="">
    <div class="container">
        <div class="title">
            <h1>title</h1>
            <h2>subtitle</h2>
        </div>
    </div>
</header>
</body>

CSS:

body {
    max-width: 900px;
    margin: 0 auto;
    text-align: center;
}
header {
    position: relative;
}
img {
    object-fit: cover;
}
.container {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    top: 0;
    background: linear-gradient(bottom, rgba(0,0,0,1), rgba(0,0,0,.1));
    background: -webkit-linear-gradient(bottom, rgba(0,0,0,1), rgba(0,0,0,.1));
    background: -moz-linear-gradient(bottom, rgba(0,0,0,1), rgba(0,0,0,.1));
}
.title {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
}

Solution

  • It's odd that your code is doing this but try to make the img 100% the width of the container.

    Otherwise experiment a little, if you want the header, container and image to be the width of the screen, set the width of header to 100vh and then set the container and image to 100%

    img {
        width: 100%;
    }