[英]Zoom or crop a background image instead of stretching it
我有一個背景圖像 ,它占據了瀏覽器窗口的整個寬度。 此背景圖像應具有固定高度,例如500 px。
當它的寬高比接近瀏覽器窗口時,我試圖讓這個圖像盡可能完整,然后縮放或裁剪圖像的一部分(例如中間)而不是拉伸它或者當瀏覽器窗口變大時,只顯示它的一面。
這是我想要得到的一個例子:
這是一個當前如何工作的小提琴: https : //jsfiddle.net/bb61c412/
這是當前的HTML代碼:
<!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://bootswatch.com/bower_components/bootstrap/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="https://bootswatch.com/cosmo/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </head> <body> <div class="navbar navbar-default navbar-fixed-top "> <div class="container"> <div class="navbar-header"> <a href="#" class="navbar-brand">website</a> <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main"> <span class="icon-bar"></span> </button> </div> </div> </div> <div style="width:100vw; height: 500px; background-image: url(https://upload.wikimedia.org/wikipedia/commons/8/80/Paul_Gauguin_088.jpg); background-repeat: no-repeat;"> </div>
添加background-size:cover
它
正如@theblackgigant所說,你必須將background-size
屬性設置為' enter code here
封面。 您還可以設置background-position: bottom center
以使其具有正確的行為https://jsfiddle.net/bb61c412/2/
你的代碼應該是這樣的:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://bootswatch.com/bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://bootswatch.com/cosmo/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top ">
<div class="container">
<div class="navbar-header">
<a href="#" class="navbar-brand">website</a>
<button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main">
<span class="icon-bar"></span>
</button>
</div>
</div>
</div>
<div style="width:100vw; height: 677px; background-image: url(https://upload.wikimedia.org/wikipedia/commons/8/80/Paul_Gauguin_088.jpg); background-repeat: no-repeat;background-size:cover">
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.