[英]How to stretch background-image in html and css styling?
嘗試以下方法,看看最適合您的需求...
.fill {object-fit: fill;}
.contain {object-fit: contain;}
.cover {object-fit: cover;}
.scale-down {object-fit: scale-down;}
.none {object-fit: none;}
CSS object-fit屬性的所有值object-fit屬性可以具有以下值:
- fill-這是默認設置。 替換內容的大小可填充元素的內容框。 如有必要,將拉伸或擠壓物體以適合物體
- 包含-替換后的內容按比例縮放以保持其縱橫比,同時適合元素的內容框
- 封面-替換內容的大小確定為在填充元素的整個內容框時保持其長寬比。 該對象將被裁剪以適合
- 無-替換后的內容不會調整大小
- 縮小-內容的大小就像未指定內容或包含內容一樣(將導致較小的具體對象大小)
H2 { font-size:200%; color:#6a78c2; text-align:center; font-family: fantasy; } .myimgs { border:1px solid #333; background:#ff0653; padding:10px; margin-bottom:20px; } .myimg { width:100%; background-position:center; background-repeat: no-repeat; } .fill {object-fit: fill;} .cover {object-fit: cover;} .contain {object-fit: contain;} .scale-down {object-fit: scale-down;} .none {object-fit: none;}
<H2>FILL</H2> <div class="myimgs"> <img src="https://i.imgur.com/67jSBl0.jpg" alt="you" class="myimg fill" width="1049px" height="693px"> </div> <H2>COVER</H2> <div class="myimgs"> <img src="https://i.imgur.com/67jSBl0.jpg" alt="you" class="myimg cover" width="1049px" height="693px"> </div> <H2>CONTAIN</H2> <div class="myimgs"> <img src="https://i.imgur.com/67jSBl0.jpg" alt="you" class="myimg contain" width="1049px" height="693px"> </div> <H2>SCALE-DOWN</H2> <div class="myimgs"> <img src="https://i.imgur.com/67jSBl0.jpg" alt="you" class="myimg scale-down" width="1049px" height="693px"> </div> <H2>NONE</H2> <div class="myimgs"> <img src="https://i.imgur.com/67jSBl0.jpg" alt="you" class="myimg none" width="1049px" height="693px"> </div>
盡量不要將背景放在您的<body>
,而是使用#background {position: fixed; z-index: 1; background-image: url(backgroundimage.jpg); background-repeat: no-repeat; height: 100vh; width: 100vw;}
創建一個<div id="background"></div>
#background {position: fixed; z-index: 1; background-image: url(backgroundimage.jpg); background-repeat: no-repeat; height: 100vh; width: 100vw;}
#background {position: fixed; z-index: 1; background-image: url(backgroundimage.jpg); background-repeat: no-repeat; height: 100vh; width: 100vw;}
(不要忘記在第一個內容層上應用z-index> 1來使背景成為背景)。
background-position: center;
background-size: contain;
background-repeat: no-repeat;
您需要將圖像背景位置添加到中心並將重復設置為無重復。
您可以嘗試此代碼
body{
background-image: url(backgroundimage.jpg);
/*background-color: #95afc0;*/
background-repeat:no-repeat;
background-size: cover;
}
封面:調整背景圖像的大小以覆蓋整個容器,即使它必須拉伸圖像或從邊緣之一上切掉一點點
為防止背景圖像重復,您需要添加以下css屬性和值:
background-repeat: no-repeat;
有關背景屬性的更多信息,請訪問此鏈接: https : //css-tricks.com/almanac/properties/b/background/
您需要添加background-position:center(指向X和Y軸); 背景重復:不重復;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.