Dynamically resize div for background image

眉间皱痕 提交于 2019-12-24 14:52:26

问题


I have a background image in a header that automatically resizes to the width of the window. However, the height does not adjust properly -- an inherited CSS property sets the div to a fixed height of 50px.

Currently, I'm using:

background-size: cover;

I can specify a fixed height for the div that will be observed, but then the background is only correct at a specific window size. If I set the size to auto or 100%, it goes to 50px; How can I make it ignore the height it thinks it should be and just autoresize the header div to a background image that adjusts to window size?


回答1:


The div will not expand to accommodate the background image. If you always want to show the full image and have it expand with the div, you can sort of fake the background by using an image tag and some sneaky positioning instead.

img.header-image {
    width: 100%;
    height: 100%;
}

div.header-wrapper {
    position: relative;
}

div.header-contents {
    position: absolute;
    width: 100%;
    top: 0;
    color: #ffffff;
}
<div class="header-wrapper">
    <img class="header-image" alt="Cat Background" src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcR39_wPEnBeSEOiHXW1Lc0rwqhEVktULcqnvDDA4J-DZL0gndic" />
    <div class="header-contents">Here are some header contents.</div>
</div>
<div class="body-contents">And some regular content.</div>



回答2:


you have tried to use a specific size like this ?

background-size: 100% 100%;


来源:https://stackoverflow.com/questions/32129643/dynamically-resize-div-for-background-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!