Programing

백그라운드에서 CSS 이미지 확장 및 크기 조정-CSS 만 사용

lottogame 2020. 9. 29. 07:08
반응형

백그라운드에서 CSS 이미지 확장 및 크기 조정-CSS 만 사용


브라우저 뷰포트 크기에 따라 배경 이미지가 늘어나고 크기가 조정되기를 원합니다.

예를 들어 Stretch 및 Scale CSS 배경과 같은 작업을 수행하는 Stack Overflow에 대한 몇 가지 질문을 보았습니다 . 잘 작동하지만 태그가 background아닌을 사용하여 이미지를 배치하고 싶습니다 img.

img안에 태그가 배치되고 CSS로 img태그에 찬사를 보냅니다 .

width:100%; height:100%;

작동하지만 그 질문은 약간 오래되었으며 CSS 3에서 배경 이미지 크기를 조정하면 꽤 잘 작동한다고 말합니다. 예제를 처음 시도했지만 제대로 작동하지 않았습니다.

background-image선언 으로 수행하는 좋은 방법이 있습니까?


CSS3에는 background-size:cover.

이렇게하면 가로 세로 비율을 유지하면서 배경 영역이 배경 이미지로 완전히 덮 이도록 이미지 크기가 조정됩니다. 전체 영역이 커버됩니다. 그러나 크기 조정 된 이미지의 너비 / 높이가 너무 크면 이미지의 일부가 보이지 않을 수 있습니다.


CSS3 속성을 사용하여 아주 멋지게 할 수 있습니다. 비율에 맞게 크기가 조정되어 이미지 왜곡이 없습니다 (작은 이미지를 업 스케일하더라도). 아직 모든 브라우저에서 구현되지는 않았습니다.

background-size: 100%;

내가 언급 한 코드를 사용하여 ...

HTML

<div id="background">
    <img src="img.jpg" class="stretch" alt="" />
</div>

CSS

#background {
    width: 100%; 
    height: 100%; 
    position: fixed; 
    left: 0px; 
    top: 0px; 
    z-index: -1; /* Ensure div tag stays behind content; -999 might work, too. */
}

.stretch {
    width:100%;
    height:100%;
}

그러면 원하는 효과가 생성됩니다. 배경이 아닌 콘텐츠 만 스크롤됩니다.

배경 이미지는 모든 화면 크기에 맞게 브라우저 뷰포트에 맞게 크기가 조정됩니다. 콘텐츠가 브라우저 뷰포트에 맞지 않고 사용자가 페이지를 스크롤해야하는 경우 콘텐츠가 스크롤되는 동안 배경 이미지는 뷰포트에 고정 된 상태로 유지됩니다.

CSS 3를 사용하면 훨씬 더 쉬울 것 같습니다.


CSS :

html,body {
    background: url(images/bg.jpg) no-repeat center center fixed;
    -webkit-background-size: cover; /* For WebKit*/
    -moz-background-size: cover;    /* Mozilla*/
    -o-background-size: cover;      /* Opera*/
    background-size: cover;         /* Generic*/
}

background-size: 100% 100%; 

두 축의 전체 요소를 채우기 위해 배경을 늘립니다.


다음 CSS 부분은 모든 브라우저에서 이미지를 늘려야합니다.

각 페이지에 대해 동적으로 수행합니다. 따라서 PHP를 사용하여 각 페이지에 대해 고유 한 HTML 태그를 생성합니다. 모든 사진은 'image'폴더에 있으며 'Bg.jpg'로 끝납니다.

<html style="
      background: url(images/'.$pic.'Bg.jpg) no-repeat center center fixed;
      -webkit-background-size: cover;
      -moz-background-size: cover;
      -o-background-size: cover;
      background-size: cover;
      filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'images/'.$pic.'Bg.jpg\',     sizingMethod=\'scale\');
      -ms-filter: \"progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'images/'.$pic.'Bg.jpg\', sizingMethod=\'scale\')\
";>

모든 페이지에 대해 하나의 배경 그림 만있는 경우 $pic변수를 제거하고 이스케이프 백 슬래시를 제거하고 경로를 조정하고이 코드를 CSS 파일에 배치 할 수 있습니다.

html{
    background: url(images/homeBg.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/homeBg.jpg',     sizingMethod='scale');
    -ms-filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/homeBg', sizingMethod='scale');
}

이는 Internet Explorer 9, Chrome 21 및 Firefox 14에서 테스트되었습니다.


실제로 img 태그를 사용하여 배경 이미지와 동일한 효과를 얻을 수 있습니다. Z- 색인을 다른 모든 것보다 낮게 설정하고 position : absolute를 설정하고 전경의 모든 상자에 투명한 배경을 사용하기 만하면됩니다.


이 CSS 사용 :

background: url('img.png') no-repeat; 
background-size: 100%;

CSS 트릭으로 설명됩니다. 완벽한 전체 페이지 배경 이미지

데모 : https://css-tricks.com/examples/FullPageBackgroundImage/progressive.php

암호:

body {
  background: url(images/myBackground.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

이 클래스를 CSS 파일에 추가 할 수 있습니다.

.stretch {
    background: url(images/bg.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

다음에서 작동합니다.

  • Safari 3 이상
  • Chrome Whatever 이상
  • Internet Explorer 9 이상
  • Opera 10 이상 (Opera 9.5는 지원 background-size되지만 키워드는 지원 되지 않음)
  • Firefox 3.6 이상 (Firefox 4는 비 공급 업체 접두사 버전을 지원함)

컨테이너 크기에 따라 이미지의 크기를 적절하게 조정하려면 다음을 사용하십시오.

background-size: contain;
background-repeat: no-repeat;

나는 이것을 사용하고 모든 브라우저에서 작동합니다.

<html>
    <head>
        <title>Stretched Background Image</title>
        <style type="text/css">
            /* Remove margins from the 'html' and 'body' tags, and ensure the page takes up full screen height. */
            html, body {height:100%; margin:0; padding:0;}

            /* Set the position and dimensions of the background image. */
            #page-background {position:fixed; top:0; left:0; width:100%; height:100%;}

            /* Specify the position and layering for the content that needs to appear in front of the background image. Must have a higher z-index value than the background image. Also add some padding to compensate for removing the margin from the 'html' and 'body' tags. */
            #content {position:relative; z-index:1; padding:10px;}
        </style>
        <!-- The above code doesn't work in Internet Explorer 6. To address this, we use a conditional comment to specify an alternative style sheet for IE 6. -->
        <!--[if IE 6]>
        <style type="text/css">
            html {overflow-y:hidden;}
            body {overflow-y:auto;}
            #page-background {position:absolute; z-index:-1;}
            #content {position:static;padding:10px;}
        </style>
        <![endif]-->
    </head>
    <body>
        <div id="page-background"><img src="http://www.quackit.com/pix/milford_sound/milford_sound.jpg" width="100%" height="100%" alt="Smile"></div>
        <div id="content">
            <h2>Stretch that Background Image!</h2>
            <p>This text appears in front of the background image. This is because we've used CSS to layer the content in front of the background image. The background image will stretch to fit your browser window. You can see the image grow and shrink as you resize your browser.</p>
            <p>Go on, try it - resize your browser!</p>
        </div>
    </body>
</html>

감사!

그러나 누군가가 부족한 점을 말할 때까지 Google ChromeSafari 브라우저 에서 작동하지 않았습니다 (늘리는 것은 작동했지만 사진의 높이는 2mm였습니다!) .

설정하려고 height:auto;min-height:100%;

따라서 귀하의 height:100%;라인에 대해 변경하십시오 .

#### #background {
    width: 100%; 
    height: 100%; 
    position: fixed; 
    left: 0px; 
    top: 0px; 
    z-index: -1;
}

.stretch {
    width:100%;
    height:auto;
    min-height:100%;
}

새로 추가 된 코드 직전에 Drupal Tendu 테마에 style.css다음이 있습니다.

html, body {height : 100 %;}

#page {배경 : #ffffff; 높이 : 자동! 중요; 높이 : 100 %; 최소-높이 : 100 %; 위치 : 상대;}

그런 다음 다음을 추가하는 동안 사진으로 Drupal 내에 새 블록을 만들어야합니다 class=stretch.

< img alt="" class="stretch" src="pic.url" />

Just copying a picture with the editor in that Drupal block doesn't work; one has to change the editor to non-formatted text.


I agree with the image in absolute div with 100% width and height. Make sure you set 100% width and height for the body in the CSS and set margins and padding to zero. Another issue you will find with this method is that when selecting text, the selection area can sometimes encompass the background image, which has the unfortunate effect of making the full page have the selected state. You can get round this by using the user-select:none CSS rule, like so:

<html>
    <head>
        <style type="text/css">

            html,body {
                height: 100%;
                width: 100%
                margin: none;
                padding: none;
            }

            #background {
                width: 100%;
                height: 100%;
                position: fixed;
                left: 0px;
                top: 0px;
                z-index: -99999;
                -webkit-user-select: none;
                -khtml-user-select: none;
                -moz-user-select: none;
                -o-user-select: none;
                user-select: none;
            }

            #background img {
                width: 100%;
                height: 100%;
            }

            #main{ z-index:10;}
        </style>
    </head>
    <body>
        <div id="main">
            content here
        </div>
        <div id="background"><img src="bg.jpg"></div>
    </body>
</html>

Again, Internet Explorer is the bad guy here, because it doesn't recognise the user-select option - not even Internet Explorer 10 preview supports it, so you have the option of either using JavaScript to prevent background image selection (for example, http://www.felgall.com/jstip35.htm ) or using CSS 3 background-stretch method.

Also, for SEO I would put the background image at the bottom of the page, but if the background image takes too long to load (that is, with a white background initially), you could move to the top of the page.


I wanted to center and scale a background image, without stretching it to the entire page, and I wanted the aspect ratio to be maintained. This worked for me, thanks to the variations suggested in other answers:

INLINE IMAGE: ------------------------

<div id="background">
    <img src="img.jpg" class="stretch" alt="" />
</div>

CSS ----------------------------------

html {
    height:100%;
}

#background {
    text-align: center;
    width: 100%; 
    height: 100%; 
    position: fixed;
    left: 0px; 
    top: 0px; 
    z-index: -1;
}

.stretch {
    margin: auto;
    height:100%;
}

I used a combination of the background-X CSS properties to achieve the ideal scaling background image.

background-size: cover;
background-repeat: no-repeat;
background-position: center;
background-attachment: fixed;

This makes the background always cover the entire browser window and remains centered when scaling.


Use the Backstretch plugin. One could even have several images slide. It also works within containers. This way for example one could have only a portion of the background been covered with an background image.

Since even I could get it to work proves it to be an easy to use plugin :).


If you want to have the content centered horizontally, use a combination like this:

background-repeat: no-repeat;
background-size: cover;
background-position: center;

This will look beautiful.


Use this CSS:

background-size: 100% 100%


You can use the border-image : yourimage property to scale the image up to the border. Even if you give the background-image, the border image will be drawn over it.

The border-image property is very useful if your style sheet is implemented somewhere which doesn't support CSS 3. If you are using Google Chrome or Firefox, then I recommend the background-size:cover property itself.


Do you want to achieve this just using one image? Because you can actually make somewhat similar to a stretching background using two images. PNG images for instance.

I've done this before, and it's not that hard. Besides, I think stretching would just harm the quality of the background. And if you add a huge image it would slow down slow computers and browsers.

참고URL : https://stackoverflow.com/questions/1150163/stretch-and-scale-a-css-image-in-the-background-with-css-only

반응형