简体   繁体   中英

Image is not the size it should be HTML/CSS

I've got this problem with the banner in the page I just started to create. I'm a beginner in html and couldn't find any similar questions here so sorry if this has been answered before, ok now to the point. I have this on my stylesheet:

body            {
            width: 900px;
            margin: auto;
            max-width: 900px;
            min-width: 300px;
            background-attachment: fixed;
            background-size: cover;
            background-image: url(images/seagull-sunset2.jpg);
            }

#banner img     {
            width: 100%;
            height: 200px;
            max-width: 100%;
            box-shadow: 2.5px 2.5px 5px 2.5px rgba(240,168,48,0.5);
            }

From this I think the banner img should be 900px or just as big as its parent div is but for some reason the banner is still around 20-30 px smaller than the body and when I set its width to 900px instead of 100% the image kinda aligns to the right and gets out of the body. Thanks in advance for your help

If you want to fully contain the image, then try this:

background-size: contain;
background-position: center center;

But please note that the body has the same size as the client has set it, so it will not always be 900px in width.

you just need to add this to your css and the problem will be fixed

#banner{
  margin:0;
}

You cannot set a width on the body tag other than 100% because you cannot control how wide a user's browser window will be. If 900px must be the width of your content then try adding a div tag after the body tag around all the other content like so:

<body>
<div class="wrapper">
<figure id="banner">
    <img src="" />
</figure>
</div>
</body>

And then use this css:

body {
    width: 100%;
    background-attachment:fixed;
    background-size: cover;
    background-position: center;
    background-image: url(images/seagull-sunset2.jpg);
}

.wrapper {
    width: 96%;
    max-width: 900px;
    margin: 0 auto;
}

Your content will go to a maximum of 900px width, and the image on your body will size to fit the width of the browser window, regardless of whether the pixel width of it is less than 900px. The picture will automatically fill the space available.

Additionally the 96% width of the wrapper will ensure that your content sits in the middle of the browser window with a 2% margin left and right, when the browser window is less than 900px wide.

Also set your img css like so:

#banner img {
    width: 100% !important;
    height: auto !important;
}

This will ensure the image is sized to the full width of the banner, and also so it is not squashed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM