簡體   English   中英

div全寬度的響應背景圖像

[英]Responsive background image in div full width

我試圖找出如何在div全寬和響應中制作背景圖像。 背景圖像在頁面寬度上擴展(並且響應),但圖像的高度不是其全高。 似乎它正以某種方式被切斷。 我正在使用bootstrap框架,我試圖這樣做的原因是我想在圖像上疊加一些文本。 我嘗試了很多不同的東西,但似乎無法弄明白,幫助!

<div class="bg-image">
  <div class="container">
    <div class="row-fluid">
      <div class="span12">
        <h1>This is some text</h1>
      </div>
    </div>
  </div>
</div>


  .bg-image {
  background: url(img/image.jpg) no-repeat center top;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  max-height: 450px;
  }

這是獲得您想要的設計的一種方法。

從以下HTML開始:

<div class="container">
    <div class="row-fluid">
        <div class="span12">
            <div class="nav">nav area</div>
            <div class="bg-image">
                <img src="http://unplugged.ee/wp-content/uploads/2013/03/frank2.jpg">
                 <h1>This is centered text.</h1>
            </div>
            <div class="main">main area</div>
        </div>
    </div>
</div>

請注意,背景圖像現在是文檔常規流程的一部分。

應用以下CSS:

.bg-image {
    position: relative;
}
.bg-image img {
    display: block;
    width: 100%;
    max-width: 1200px; /* corresponds to max height of 450px */
    margin: 0 auto;
}
.bg-image h1 {
    position: absolute;
    text-align: center;
    bottom: 0;
    left: 0;
    right: 0;
    color: white;
}
.nav, .main {
    background-color: #f6f6f6;
    text-align: center;
}

這是如何工作的

圖像設置為寬度為100%的常規流內容,因此它將根據父容器的寬度進行自我調整。 但是,您希望高度不超過450px,這對應於1200px的圖像寬度,因此將圖像的最大寬度設置為1200px。 您可以使用display: blockmargin: 0 auto來保持圖像居中。

使用絕對定位在文本上繪制文本。 在最簡單的情況下,我將h1元素拉伸為父元素的整個寬度,並使用text-align: center center將文本居中。 使用頂部或底部偏移將文本放置在需要的位置。

如果橫幅圖像的寬高比會有所不同,則需要使用jQuery / Javascript動態調整.bg-image img的最大寬度值,否則,這種方法可以提供很多。

請參閱演示: http//jsfiddle.net/audetwebdesign/EGgaN/

當您使用background-size: cover ,背景圖像將自動拉伸以覆蓋整個容器。 但是,長寬比會保持不變,因此除非圖像的寬高比和應用的元素相同,否則您將始終丟失部分圖像。

我看到兩種方法可以解決這個問題:

  • 不要通過設置background-size: 100% 100% 保持圖像的縱橫比 background-size: 100% 100%這也會使圖像覆蓋整個容器,但不會保持比例。 缺點是這會扭曲您的圖像,因此可能看起來非常奇怪,具體取決於圖像。 隨着你在小提琴中使用的圖像,我認為你可以逃脫它。

  • 您還可以使用javascript根據寬度計算和設置元素的高度 ,因此它與圖像的比例相同。 此計算必須在加載和調整大小時完成。 使用幾行代碼應該很容易(如果你想要一個例子,可以隨意詢問)。 這種方法的缺點是您的寬度可能變得非常小(在移動設備上),因此計算的高度也會變小,這可能導致容器的內容溢出。 這可以通過改變內容的大小來解決,但它增加了解決方案的一些復雜性/

我也試過這種風格的離子混合應用程序背景。 這也有背景模糊效果的風格。

.bg-image {
   position: absolute;
   background: url(../img/bglogin.jpg) no-repeat;
   height: 100%;
   width: 100%;
   background-size: cover;
   bottom: 0px;
   margin: 0 auto;
   background-position: 50%;


  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM