簡體   English   中英

使用CSS創建流暢的背景圖片

[英]Create Fluid Background Image with CSS

我正在嘗試構建一個可以根據屏幕尺寸調整大小的簡單流體圖像。

但是當瀏覽器的寬度變小時,我很難使圖像變小。

HTML:

<main>
    <section class="slider-ctn">
        <figure class="logo"></figure>
    </section>
</main>

CSS:

.slider-ctn figure.logo {
    margin: auto;
    background-image: url('../Images/logo.200x100.png');
    width: 200px;
    height: 100px;
}

如果你設置background-size ,以100% 100%cover圖像將延伸到適合的容器。 刪除寬度(或通過設置父級的寬度限制寬度)並設置height: 0; padding-top: 50% height: 0; padding-top: 50%在圖形上height: 0; padding-top: 50% ,以使圖形的高度為寬度的一半,因此長寬比將與圖像匹配並且流暢。

 * {margin:0;padding:0;} .slider-ctn { margin: auto; width: 200px; } .slider-ctn figure.logo { background: url('https://dummyimage.com/200x100/000/fff') top left no-repeat; height: 0; background-size: cover; padding-top: 50%; } 
 <main> <section class="slider-ctn"> <figure class="logo"></figure> </section> </main> 

只需使用以下代碼將以下內容添加到您的head標簽中:

<meta name="viewport" content="width=device-width, initial-scale=1">

您應該將contain作為背景大小添加到CSS:

.slider-ctn figure.logo {
  margin: auto;
  background-image: url('../Images/logo.200x100.png');
  background-position:center center;
  background-repeat:no-repeat;
  background-size:contain;
  width: 200px;
  max-width:100%;
  height: 100px;
  display:inline-block;
}

使用背景圖像時,請不要忘記每次在背景屬性中添加positionrepeat

另外,如果它小於徽標容器,我還添加了max-width以適合父容器。

這里的例子

注意:請勿使用背景尺寸的cover ,因為這樣會切掉徽標,使其僅適合width限制, contain將適合widthheight

使用大眾單位和包含的另一種選擇。

如果知道圖像的縱橫比,則可以使用vw(視圖寬度)作為寬度和高度的單位。

我正在使用長寬比為4x3的圖像。 如果我希望寬度始終是屏幕的80%,我將使用80vw。 然后,我的身高將是寬度的3/4,即60vw。

然后,請確保使用contain作為背景大小。

試試這個CSS,看看它是否滿足您的需求:

.slider-ctn figure.logo { margin: auto; background-image: url('https://i.ytimg.com/vi/tntOCGkgt98/maxresdefault.jpg'); background-size: contain; background-repeat: no-repeat; width: 80vw; height: 60vw; border: 5px solid red; }

我認為將圖像的最大寬度設置為100%應該可以解決問題。

.slider-ctn figure.logo {
  background-image: url('../Images/logo.200x100.png');
  background-repeat:no-repeat;
  background-size:contain;
  background-position:center;
  width: 200px;
  height: 100px;
}

暫無
暫無

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

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