programing

바닥글을 웹 페이지 하단에 유지하려면 어떻게 해야 합니까?

stoneblock 2023. 9. 1. 20:32

바닥글을 웹 페이지 하단에 유지하려면 어떻게 해야 합니까?

마크업에서 오른쪽과 왼쪽 div를 모두 지울 수 있는 바닥글이 있는 간단한 2열 레이아웃이 있습니다.문제는 모든 브라우저에서 바닥글을 페이지 맨 아래에 유지할 수 없다는 것입니다.내용이 바닥글을 아래로 밀면 작동하지만 항상 그렇지는 않습니다.

스티커 바닥글을 가져오는 방법

  1. 을 가지다<div>와 함께class="wrapper"당신의 만족을 말씀해주세요.

  2. 마감 직전</div>의 시대의wrapper을 배치합니다.<div class="push"></div>.

  3. 마감직후</div>의 시대의wrapper을 배치합니다.<div class="footer"></div>.

* {
    margin: 0;
}
html, body {
    height: 100%;
}
.wrapper {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */
}
.footer, .push {
    height: 142px; /* .push must be the same height as .footer */
}
<div class="wrapper">wrapper
    <div class="push">push</div>
</div>
<div class="footer">footer</div>

CSS vh 단위 사용!

스티커 푸터를 사용하는 가장 확실하고 비해킹적인 방법은 새로운 CSS 뷰포트 유닛을 사용하는 것일 것입니다.

다음과 같은 단순 마크업을 예로 들어 보겠습니다.

<header>header goes here</header>
<div class="content">This page has little content</div>
<footer>This is my footer</footer>

헤더가 80px high이고 바닥글이 40px high인 경우 div 컨텐츠에 대한 단일 규칙으로 스티커형 바닥글을 만들 수 있습니다.

.content {
    min-height: calc(100vh - 120px);
    /* 80px header + 40px footer = 120px  */
}

즉, 내용 div의 높이는 뷰포트 높이에서 머리글과 바닥글의 결합된 높이를 뺀 100% 이상이어야 합니다.

바로 그겁니다.

* {
    margin:0;
    padding:0;
}
header {
    background: yellow;
    height: 80px;
}
.content {
    min-height: calc(100vh - 120px);
    /* 80px header + 40px footer = 120px  */
    background: pink;
}
footer {
    height: 40px;
    background: aqua;
}
<header>header goes here</header>
<div class="content">This page has little content</div>
<footer>This is my footer</footer>

그리고 다음은 컨텐츠 디비에 있는 많은 콘텐츠에서 동일한 코드가 작동하는 방법입니다.

* {
    margin:0;
    padding:0;
}
header {
    background: yellow;
    height: 80px;
}
.content {
    min-height: calc(100vh - 120px);
    /* 80px header + 40px footer = 120px  */
    background: pink;
}
footer {
    height: 40px;
    background: aqua;
}
<header>header goes here</header>
<div class="content">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.
</div>
<footer>
    This is my footer
</footer>

NB:

머리글과 바닥글의 높이를 알아야 합니다.

이전 버전의 IE(IE8-) 및 Android(4.4-)는 뷰포트 유닛을 지원하지 않습니다.(caniuse)

옛날에 웹킷이 계산 규칙 내에서 뷰포트 단위에 문제가 있었습니다.이것은 확실히 수정되었기 때문에 (여기를 참조하십시오) 거기에는 문제가 없습니다.하지만 어떤 이유로 계산을 사용하는 것을 피하려고 한다면 마이너스 마진과 박스 크기의 패딩을 사용하는 것을 피할 수 있습니다.

이와 같은 경우:

* {
    margin:0;padding:0;
}
header {
    background: yellow;
    height: 80px;
    position:relative;
}
.content {
    min-height: 100vh;
    background: pink;
    margin: -80px 0 -40px;
    padding: 80px 0 40px;
    box-sizing:border-box;
}
footer {
    height: 40px;
    background: aqua;
}
<header>header goes here</header>
<div class="content">Lorem ipsum 
</div>
<footer>
    This is my footer
</footer>

은 " 스커부바글"로 표시됩니다.display: flex

필립 월튼의 끈적끈적한 바닥글에서 영감을 얻은 솔루션입니다.

설명.

솔루션은 다음에 대해서만 유효합니다.

  • 크롬 » 21.0
  • 파이어폭스 » 20.0
  • Internet Explorer » 10
  • Safari » 6.1

디스플레이를 기반으로 합니다.flex-grow속성, 요소가 높이 또는 에서 성장할 수 있도록 합니다.flow-direction다음 중 하나로 설정됩니다.column또는row각각), 컨테이너의 추가 공간을 차지합니다.

우리는 또한 활용할 것입니다.vh서 단위, 치위1vh다음과 같이 정의됩니다.

뷰포트 높이의 100분의 1

러므로 의높 이그의 입니다.100vh요소가 전체 뷰포트 높이에 걸쳐지도록 지시하는 간결한 방법입니다.

웹 페이지를 구성하는 방법은 다음과 같습니다.

----------- body -----------
----------------------------

---------- footer ----------
----------------------------

바닥글을 페이지 하단에 고정하려면 본문과 바닥글 사이의 공간을 페이지 하단에 있는 바닥글을 누르는 데 필요한 만큼 늘립니다.

따라서 레이아웃은 다음과 같습니다.

----------- body -----------
----------------------------

---------- spacer ----------
                             <- This element must grow in height
----------------------------

---------- footer ----------
----------------------------

실행

body {
    margin: 0;
    display: flex;
    flex-direction: column;
    min-height: 100vh;
}

.spacer {
    flex: 1;
}

/* make it visible for the purposes of demo */
.footer {
    height: 50px;
    background-color: red;
}
<body>
    <div class="content">Hello World!</div>
    <div class="spacer"></div>
    <footer class="footer"></footer>
</body>

JS Fiddle에서 가지고 놀 수 있습니다.

사파리 퀘이크

Safari에는 콘텐츠를 표시하는 데 필요한 최소 높이 이상으로 항목을 축소할 수 있는 결함이 있는 속성 구현이 있습니다.이 문제를 해결하려면 다음을 설정해야 합니다.flex-shrink합니다..content 리고그고.footer위의 예에서:

.content {
  flex-shrink: 0;
}

.footer {
  flex-shrink: 0;
}

또는 다음을 변경합니다.flexspacer요소 입력:

.spacer {
  flex: 1 0 auto;
}

이 3값 단축형은 다음과 같은 전체 설정과 동일합니다.

.spacer {
  flex-grow: 1;
  flex-shrink: 0;
  flex-basis: auto;
}

어디서나 우아하게 작동합니다.

사용할 수 있습니다.position: absolute 맨 두의 열에 한 페지하에바닥놓다수행되하, 두개열적내확다있인니합는지용이한합에의을음면이려으단을글▁가 있는지 확인합니다.margin-bottom바닥글에 가려지지 않도록 합니다.

#footer {
    position: absolute;
    bottom: 0px;
    width: 100%;
}
#content, #sidebar { 
    margin-bottom: 5em; 
}

여기 매력적으로 작동하는 jQuery의 솔루션이 있습니다.그것은 창문의 높이가 몸의 높이보다 큰지 확인합니다.이 경우 바닥글의 여백 상단을 변경하여 보정합니다.Firefox, Chrome, Safari 및 Opera에서 테스트되었습니다.

$( function () {

    var height_diff = $( window ).height() - $( 'body' ).height();
    if ( height_diff > 0 ) {
        $( '#footer' ).css( 'margin-top', height_diff );
    }

});

바닥글에 여백 상단(예: 50픽셀)이 이미 있는 경우 마지막 부분을 변경해야 합니다.

css( 'margin-top', height_diff + 50 )

"CSS"에 합니다.#footer대상:

position: absolute;
bottom: 0;

그면다추합니다야를 해야 합니다.padding또는margin#sidebar그리고.#content#footer겹쳤을 는 는그들겹때칠이또,때▁or▁the▁when,칠▁they겹.#footer그들을 커버할 것입니다.

제는 는한, 제이맞다면, IE6는 또니다에 .bottom: 0CSS. IE6에 JS 솔루션을 사용해야 할 수도 있습니다(IE6에 관심이 있다면).

@gcedo와 유사한 솔루션이지만 바닥글을 아래로 밀어넣기 위해 중간 콘텐츠를 추가할 필요가 없습니다.간단히 추가할 수 있습니다.margin-top:auto바닥글로 이동하면 사용자의 높이나 위 내용의 높이에 관계없이 페이지 하단으로 이동됩니다.

body {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  margin:0;
}

.content {
  padding: 50px;
  background: red;
}

.footer {
  margin-top: auto;
  padding:10px;
  background: green;
}
<div class="content">
  some content here
</div>
<footer class="footer">
  some content
</footer>

저에게 아주 간단한 해결책을 발명했습니다.디브 안에 있는 바닥글을 제외한 모든 페이지 내용을 랩핑한 다음 최소 높이를 바닥글 높이를 뺀 시점의 100%로 설정합니다.바닥글이나 여러 래퍼 디브에 절대적으로 위치할 필요가 없습니다.

.page-body {
    min-height: calc(100vh - 400px);
} /*Replace 400px with your footer height*/

저는 가끔 이 문제로 어려움을 겪었고, 항상 서로의 내부에 모든 디비가 있는 해결책이 엉망이라는 것을 알았습니다.저는 그것을 조금 만지작거렸고, 저는 개인적으로 이것이 효과가 있다는 것을 알게 되었고, 그것은 확실히 가장 간단한 방법 중 하나입니다.

html {
    position: relative;
}

html, body {
    margin: 0;
    padding: 0;
    min-height: 100%;
}

footer {
    position: absolute;
    bottom: 0;
}

제가 이것에 대해 좋아하는 것은 추가 HTML을 적용할 필요가 없다는 것입니다.당신은 간단히 이 CSS를 추가하고 언제든지 HTML을 쓸 수 있습니다.

그리드 솔루션이 아직 제시되지 않았기 때문에, 여기에 상위 요소에 대한 단 개의 선언이 있습니다.height: 100%그리고.margin: 0당연히:

html, body {height: 100%}

body {
  display: grid; /* generates a block-level grid */
  align-content: space-between; /* places an even amount of space between each grid item, with no space at the far ends */
  margin: 0;
}

.content {
  background: lightgreen;
  /* demo / for default snippet window */
  height: 1em;
  animation: height 2.5s linear alternate infinite;
}

footer {background: lightblue}

@keyframes height {to {height: 250px}}
<div class="content">Content</div>
<footer>Footer</footer>

항목은 가로축을 따라 정렬 용기 내에서 고르게 분포됩니다.인접한 각 항목 쌍 사이의 간격은 동일합니다.첫 번째 항목은 주 시작 에지와 같은 높이이고 마지막 항목은 주 끝 에지와 같은 높이입니다.

CSS:

  #container{
            width: 100%;
            height: 100vh;
            }
 #container.footer{
            float:left;
            width:100%;
            height:20vh;
            margin-top:80vh;
            background-color:red;
            }

HTML:

           <div id="container">
               <div class="footer">
               </div>
           </div>

항상 뷰포트 높이의 80%를 상단 여백으로 유지하는 페이지 하단에 정렬된 응답 바닥글을 찾는 경우 이 방법이 유용합니다.

이 질문에 대해 제가 본 많은 답변들은 투박하고, 구현하기 어렵고, 비효율적이기 때문에, 저는 그것을 시도해보고 단지 약간의 css와 html인 저만의 해결책을 생각해내야겠다고 생각했습니다.

html,
body {
  height: 100%;
  margin: 0;
}
.body {
  min-height: calc(100% - 2rem);
  width: 100%;
  background-color: grey;
}
.footer {
  height: 2rem;
  width: 100%;
  background-color: yellow;
}
<body>
  <div class="body">test as body</div>
  <div class="footer">test as footer</div>
</body>

이것은 바닥글의 높이를 설정한 다음 CSS 계산을 사용하여 바닥글이 여전히 아래에 있을 수 있는 페이지의 최소 높이를 계산함으로써 작동합니다. 이것이 일부 사람들에게 도움이 되기를 바랍니다 :)

위치 고정을 사용하지 않고 모바일에서 짜증나게 팔로우하는 것을 원하지 않는다면, 이것은 지금까지 저에게 효과가 있는 것처럼 보입니다.

html {
    min-height: 100%;
    position: relative;
}

#site-footer {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 6px 2px;
    background: #32383e;
}

을 html로 .min-height: 100%;그리고.position: relative;,그리고나서position: absolute; bottom: 0; left: 0; 저는 했습니다.그런 다음 바닥글이 신체의 마지막 요소인지 확인했습니다.

이것이 다른 사람에게 효과가 없다면, 왜 그런지 알려주세요.저는 이런 지루한 스타일의 해킹이 제가 생각하지 못했던 다양한 상황에서 이상하게 행동할 수 있다는 것을 알고 있습니다.

절대 위치 지정 및 z-index를 사용하여 다음 단계를 사용하여 해상도에서 스티커형 바닥글 div를 만듭니다.

  • 로 div position: absolute; bottom: 0; 및 원 는 높 이 하
  • 내용 하단과 창 하단 사이에 공백을 추가하도록 바닥글의 패딩 설정
  • 를 생성합니다.div의 내용물을 position: relative; min-height: 100%;
  • 콘텐츠에 하기 주내용에단딩패가추하가추▁add▁to패딩▁padding.div입니다.
  • 을 합니다.z-index보다 큰 div

다음은 예입니다.

<!doctype html>
<html>
  <head>
    <title>Sticky Footer</title>
    <meta charset="utf-8">
    <style>
      .wrapper { position: relative; min-height: 100%; }
      .footer { position: absolute; bottom:0; width: 100%; height: 200px; padding-top: 100px; background-color: gray; }
      .column { height: 2000px; padding-bottom: 300px; background-color: grxqeen; }
      /* Set the `html`, `body`, and container `div` to `height: 100%` for IE6 */
    </style>
  </head>
  <body>
    <div class="wrapper">
      <div class="column">
        <span>hello</span>
      </div>
      <div class="footer">
        <p>This is a test. This is only a test...</p>
      </div>
    </div>
  </body>
</html>

내 사이트에서 항상 사용하는 항목:

position: fixed;

...내 CSS에서 바닥글을 찾습니다.그러면 페이지 하단에 고정됩니다.

한 가지 해결책은 상자의 최소 높이를 설정하는 것입니다.안타깝게도 IE(놀랍게도)에서 잘 지원되지 않는 것 같습니다.

이러한 순수한 CSS 솔루션 중 어떤 것도 동적으로 크기를 조정하는 컨텐츠(적어도 파이어폭스 및 Safari에서)에서 제대로 작동하지 않습니다. 예를 들어, 컨테이너 div에서 페이지를 설정한 다음 div 내부에서 크기를 조정하고 테이블을 크기를 조정(몇 줄 추가)하면 테이블이 스타일 영역의 하단 밖으로 돌출될 수 있습니다.글꼴 색과 배경 색이 모두 흰색이기 때문에 검은색 테마의 흰색 테이블과 흰색 테이블의 절반을 완성할 수 있습니다.기본적으로 롤러 페이지에는 고정할 수 없습니다.

중첩된 div 다중 열 레이아웃은 추한 해킹이고 100% 최소 높이의 바닥글 고정용 본체/컨테이너 div는 추한 해킹입니다.

내가 시도한 모든 브라우저에서 작동하는 유일한 비스크립트 솔루션: 광고(헤더용)/tfoot(바닥글용)/tbody(여러 열에 대한 td's)와 높이가 100%인 훨씬 단순한/짧은 테이블.그러나 이것은 의미론적 및 SEO 단점을 인식했습니다(tfoot은 tbody 앞에 나타나야 함).ARIA 역할은 적절한 검색 엔진에 도움이 될 수 있습니다.

여러 사람들이 이 간단한 문제에 대한 답을 여기에 올렸지만, 제가 무엇을 잘못하고 있는지 알아내기 전까지 얼마나 좌절했는지를 생각하면 한 가지 덧붙여야 할 것이 있습니다.

이를 위한 가장 간단한 방법은 다음과 같습니다.

html {
    position: relative;
    min-height: 100%;
}

body {
    background-color: transparent;
    position: static;
    height: 100%;
    margin-bottom: 30px;
}

.site-footer {
    position: absolute;
    height: 30px;
    bottom: 0px;
    left: 0px;
    right: 0px;
}

그러나 게시물에 언급되지 않은 속성은 일반적으로 기본값이기 때문에 본문 태그의 정적 위치입니다.상대 위치가 작동하지 않습니다!

제 워드프레스 테마는 기본 바디 디스플레이를 무시했고 그것은 불쾌할 정도로 오랫동안 저를 혼란스럽게 했습니다.

오래된 스레드이지만 응답성이 뛰어난 솔루션을 찾고 있다면 이 jQuery 추가 기능을 통해 다음과 같은 이점을 얻을 수 있습니다.

$(window).on('resize',sticky);
$(document).bind("ready", function() {
   sticky();
});

function sticky() {
   var fh = $("footer").outerHeight();
   $("#push").css({'height': fh});
   $("#wrapper").css({'margin-bottom': -fh});
}

전체 가이드는 https://pixeldesigns.co.uk/blog/responsive-jquery-sticky-footer/ 에서 확인할 수 있습니다.

저는 매우 간단한 도서관 https://github.com/ravinderpayal/FooterJS 을 만들었습니다.

그것은 사용법이 매우 간단합니다.라이브러리를 포함한 후에는 이 코드 라인을 호출하면 됩니다.

footer.init(document.getElementById("ID_OF_ELEMENT_CONTAINING_FOOTER"));

다른 파라미터/id로 상기 함수를 호출하여 동적으로 바닥글을 변경할 수 있습니다.

footer.init(document.getElementById("ID_OF_ANOTHER_ELEMENT_CONTAINING_FOOTER"));

참고:- CSS를 변경하거나 추가할 필요가 없습니다.라이브러리는 동적이므로 페이지를 로드한 후 화면 크기가 조정되더라도 바닥글 위치가 재설정됩니다.제가 이 라이브러리를 만든 이유는 CSS가 잠시 동안 문제를 해결해 주지만 데스크톱에서 태블릿으로 또는 그 반대로 디스플레이 크기가 크게 바뀌면 콘텐츠가 겹치거나 더 이상 끈적거리지 않기 때문입니다.

또 다른 해결책은 CSS 미디어 쿼리이지만 이 라이브러리가 자동으로 작업을 수행하고 모든 기본 자바스크립트 지원 브라우저에서 지원하는 동안 다른 크기의 화면에 대해 다른 CSS 스타일을 수동으로 작성해야 합니다.

CSS 솔루션 편집:

@media only screen and (min-height: 768px) {/* or height/length of body content including footer*/
    /* For mobile phones: */
    #footer {
        width: 100%;
        position:fixed;
        bottom:0;
    }
}

이제 디스플레이 높이가 콘텐츠 길이보다 클 경우 바닥글을 아래로 고정하고 바닥글을 보려면 스크롤해야 하므로 맨 끝에 자동으로 표시됩니다.

그리고 자바스크립트/라이브러리 솔루션보다 더 나은 솔루션인 것 같습니다.

이전에는 이 페이지에서 제안한 해결책에 대해 운이 좋지 않았지만, 마침내 이 작은 속임수가 효과가 있었습니다.저는 그것을 다른 가능한 해결책으로 포함시킬 것입니다.

footer {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 1rem;
  background-color: #efefef;
  text-align: center;
}

바닥글을 표시하는 가장 좋은 방법은 항상 내용을 가리지 않고 맨 아래에 고정하는 것입니다.

#my_footer {
    position: static
    fixed; bottom: 0
}

jQuery CROSS Browser 사용자 정의 플러그인 - $.footerBottom()

를 는또나럼처 jQuery를사바하닥높다설정다로 설정합니다.auto또는 로fix.이 플러그인은 jQuery 선택기를 사용하므로 파일에 jQuery 라이브러리를 포함해야 합니다.

플러그인을 실행하는 방법은 다음과 같습니다.jQuery 가져오기, 이 사용자 지정 jQuery 플러그인의 코드를 복사한 후 jQuery 가져오기!그것은 매우 간단하고 기본적이지만 중요합니다.

이 경우 다음 코드를 실행하기만 하면 됩니다.

$.footerBottom({target:"footer"}); //as html5 tag <footer>.
// You can change it to your preferred "div" with for example class "footer" 
// by setting target to {target:"div.footer"}

문서 준비 이벤트 내에 배치할 필요가 없습니다.그것은 그대로 잘 운영될 것입니다.페이지가 로드되고 창 크기가 조정될 때 바닥글의 위치가 다시 계산됩니다.

여기 당신이 이해할 필요가 없는 플러그인의 코드가 있습니다.구현 방법만 알면 됩니다.그것은 당신에게 도움이 됩니다.하지만, 만약 여러분이 그것이 어떻게 작동하는지 알고 싶다면, 그냥 코드를 훑어보세요.제가 댓글을 남겼습니다.

//import jQuery library before this script

// Import jQuery library before this script

// Our custom jQuery Plugin
(function($) {
  $.footerBottom = function(options) { // Or use "$.fn.footerBottom" or "$.footerBottom" to call it globally directly from $.footerBottom();
    var defaults = {
      target: "footer",
      container: "html",
      innercontainer: "body",
      css: {
        footer: {
          position: "absolute",
          left: 0,
          bottom: 0,
        },

        html: {
          position: "relative",
          minHeight: "100%"
        }
      }
    };

    options = $.extend(defaults, options);

    // JUST SET SOME CSS DEFINED IN THE DEFAULTS SETTINGS ABOVE
    $(options.target).css({
      "position": options.css.footer.position,
      "left": options.css.footer.left,
      "bottom": options.css.footer.bottom,
    });

    $(options.container).css({
      "position": options.css.html.position,
      "min-height": options.css.html.minHeight,
    });

    function logic() {
      var footerOuterHeight = $(options.target).outerHeight(); // Get outer footer height
      $(options.innercontainer).css('padding-bottom', footerOuterHeight + "px"); // Set padding equal to footer height on body element
      $(options.target).css('height', footerOuterHeight + "!important"); // Set outerHeight of footer element to ... footer
      console.log("jQ custom plugin footerBottom runs"); // Display text in console so ou can check that it works in your browser. Delete it if you like.
    };

    // DEFINE WHEN TO RUN FUNCTION
    $(window).on('load resize', function() { // Run on page loaded and on window resized
      logic();
    });

    // RETURN OBJECT FOR CHAINING IF NEEDED - IF NOT DELETE
    // return this.each(function() {
    //   this.checked = true;
    // });
    // return this;
  };
})(jQuery); // End of plugin


// USE EXAMPLE
$.footerBottom(); // Run our plugin with all default settings for HTML5
/* Set your footer CSS to what ever you like it will work anyway */
footer {
  box-sizing: border-box;
  height: auto;
  width: 100%;
  padding: 30px 0;
  background-color: black;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- The structure doesn't matter much, you will always have html and body tag, so just make sure to point to your footer as needed if you use html5, as it should just do nothing run plugin with no settings it will work by default with the <footer> html5 tag -->
<body>
  <div class="content">
  <header>
    <nav>
      <ul>
        <li>link</li>
        <li>link</li>
        <li>link</li>
        <li>link</li>
        <li>link</li>
        <li>link</li>
      </ul>
    </nav>
  </header>

  <section>
      <p></p>
      <p>Lorem ipsum...</p>
    </section>
  </div>
  <footer>
    <p>Copyright 2009 Your name</p>
    <p>Copyright 2009 Your name</p>
    <p>Copyright 2009 Your name</p>
  </footer>

플렉스 솔루션은 바닥글을 끈적하게 만드는 데까지 효과가 있었지만 불행히도 플렉스 레이아웃을 사용하도록 본문을 변경하면 페이지 레이아웃이 일부 변경되고 더 나아지지 않습니다.결국 저에게 효과가 있었던 것은:

    jQuery(document).ready(function() {

    var fht = jQuery('footer').outerHeight(true);
    jQuery('main').css('min-height', "calc(92vh - " + fht + "px)");

});

저는 이것을 https://css-tricks.com/couple-takes-sticky-footer/ 에 있는 ctf0의 응답에서 얻었습니다.

div.fixed {
   position: fixed;
   bottom: 0;
   right: 0;
   width: 100%;
   border: 3px solid #73AD21;
}
<body style="height:1500px">

   <h2>position: fixed;</h2>

   <p>An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled:</p>

   <div class="fixed">
      This div element has position: fixed;
   </div>

</body>

REACT 친화적인 솔루션 - (spacer div가 필요하지 않음)

Chris Coyier(유망한 CSS-Tricks 웹사이트)는 현재 FlexBox 및 CSS-Grid 사용을 포함하여 스틱 푸터를 만드는 최소 5가지 방법으로 스티키 푸터에 대한 페이지를 최신 상태로 유지하고 있습니다.

이것이 왜 중요합니까?몇 년 동안 사용했던 이전/이전 방법은 React와 함께 작동하지 않았기 때문입니다. Chris의 Flexbox 솔루션을 사용해야 했습니다. 이 방법은 쉽고 효과적이었습니다.

아래는 의 CSS-Tricks 플렉스박스 스틱 푸터입니다. 아래 코드를 보십시오. 이보다 더 간단할 수 없습니다.

(아래의) StackSnipet 예제는 예제의 맨 아래를 완벽하게 렌더링하지 않습니다.바닥글은 화면 하단을 지나 확장된 것으로 표시되며, 이는 실제 상황에서는 발생합니다.

html,body{height: 100%;}
body     {display:flex; flex-direction:column;}
.content {flex: 1 0 auto;} /* flex: grow / shrink / flex-basis; */
.footer  {flex-shrink: 0;}

/* ---- BELOW IS ONLY for demo ---- */
.footer{background: palegreen;}
<body>
  <div class="content">Page Content - height expands to fill space</div>
  <footer class="footer">Footer Content</footer>
</body>

Chris는 또한 그리드를 선호하는 사람들을 위해 이 CSS-Grid 솔루션을 시연합니다.


참조:

CSS-Tricks - Flexbox에 대한 전체 가이드

http://1linelayouts.glitch.me/, 사례 4를 살펴보십시오.우나 크라베츠는 이 문제를 해결합니다.

이렇게 하면 머리글, 주 페이지 및 바닥글이 있는 3층 페이지가 만들어집니다.

- 바닥글은 항상 맨 아래에 있고 내용에 맞게 공간을 사용합니다.

- 헤더는 항상 맨 위에 있고, 내용에 맞게 공간을 사용합니다.

-메인은 항상 필요한 경우 화면을 채울 수 있을 정도의 남은 공간(남은 공간)을 모두 사용합니다.

HTML

<div class="parent">
  <header class="blue section" contenteditable>Header</header>
  <main class="coral section" contenteditable>Main</main>
  <footer class="purple section" contenteditable>Footer Content</footer>
</div>
    

CSS

.parent {
  display: grid;
  height: 95vh; /* no scroll bars if few content */
  grid-template-rows: auto 1fr auto;
}
    

Flex를 사용한 빠르고 간편한 솔루션

  • 를 .html그리고.body100%
html,
body {
  width: 100%;
  height: 100%;
}
  • 을 문을다음같표로 합니다.flex와 함께column방향:
body { 
  min-height: 100%;
  display: flex;
  flex-direction: column;
}
  • 더하다flex-grow: 1에.
main {
  flex-grow: 1;
}

flex-growFlex 컨테이너의 나머지 공간 중 항목에 할당할 공간(Flex Grow 팩터)을 지정합니다.

*, 
*::after,
*::before{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
html,
body {
  width: 100%;
  height: 100%;
}

body {
  min-height: 100%;
  display: flex;
  flex-direction: column;
}

main {
  flex-grow: 1;
}

footer{
  background-color: black;
  color: white;
  padding: 1rem 0;
  display: flex; 
  justify-content: center;
  align-items: center;
}
<body> 
    <main>
        <section >
            Hero
        </section>
    </main>

    <footer >
        <div>
            <p > &copy; Copyright 2021</p>
        </div>
    </footer>
</body>

자연스러운 머리글 및 바닥글 높이의 경우 CSS Flexbox를 사용합니다.

JS 피들을 참조하십시오.

HTML

<body>
  <header>
    ...
  </header>
  <main>
    ...
  </main>
  <footer>
    ...
  </footer>
</body>  

CSS

html {
  height: 100%;
}

body {
  height: 100%;
  min-height: 100vh;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  margin: 0;
  display: flex;
  flex-direction: column;
}

main {
  flex-grow: 1;
  flex-shrink: 0;
}

header,
footer {
  flex: none;
}

당신의 관보를 <main>최소 높이의 90vh가 당신의 문제를 영원히 해결해 줄 것입니다.여기 의미론을 따르고 전체 페이지를 커버하는 데 도움이 되는 기본 구조가 있습니다.

1단계: 머리글과 바닥글을 제외한 모든 것을 주 태그 안에 보관합니다.

<body>
    <header>
        <!╌ nav, logo ╌> 
    </header>
    <main>
        <!╌ section and div ╌> 
    </main>
    <footer>
        <!╌ nav, logo ╌>
    </footer>
</body>

2단계: 최소 높이 추가: 메인의 경우 90vh

main{
    min-height: 90vh;
}

보통 머리글과 바닥글은 높이가 70px 이상이므로 이 케이스는 잘 작동하고, 시도하고, 테스트했습니다!

언급URL : https://stackoverflow.com/questions/42294/how-do-you-get-the-footer-to-stay-at-the-bottom-of-a-web-page