Почему элемент нижнего колонтитула перекрывает содержимое страницы?

Во-первых, я ОЧЕНЬ ОЧЕНЬ новичок в кодировании HTML и CSS. Я изучаю уже ровно неделю, и я подумал, что потренируюсь, чтобы попытаться помочь мне вспомнить некоторые элементы, свойства и атрибуты. Таким образом, код, который вы собираетесь увидеть, может повредить вам глаза, но любая помощь по этому вопросу будет принята с благодарностью.

Я разрабатываю веб-сайт (который, скорее всего, никогда не будет запущен даже в его окончательной форме), и я начал возиться с элементом нижнего колонтитула. Чуть позже я обнаружил, что можно сделать элемент div для нижнего колонтитула. Однако, какой бы метод я ни использовал, он всегда заканчивается текстом на моем экране. Он прилипает к нижней части страницы до тех пор, пока я не прокручиваю страницу вниз, и постоянно закрывает основной текст. Я знаю, что это, вероятно, связано с кодом CSS, стилизующим тело, но я не могу понять это.

Я сохранил его как div на данный момент, но если нижний колонтитул будет лучше использовать, пожалуйста, дайте мне знать. Я абсолютно хочу исправить любые ошибки, которые я совершаю, как только я сталкиваюсь с ними.

nav a {
  color: black;
  font-family: 'DM Sans', sans-serif;
  font-size: 1.2em;
  padding: 12px;
  text-decoration: none;
  width: 80%;
  text-align: center;
  padding-left: 5em;
  padding-right: 2em;
}

.row {
  display: flex;
}

.left-column {
  height: 40vh;
  flex: 50%;
}

.right-column {
  height: 35vh;
  flex: 50%;
  background-position: center;
  background-size: contain;
  background-repeat: no-repeat;
}

#right-col-home {
  background-image: url(https://s3.amazonaws.com/bprblogassets/blog/wp-content/uploads/2017/06/11165212/Power-Washing-Beginner.png);
  margin-top: 12em;
}

.nav-bar {
  border-width: 0em;
  border-color: ghostwhite;
  border-bottom: 0.15em solid gray;
  font-family: 'Poppins', sans-serif;
  background-color: ghostwhite;
  overflow: auto;
  padding: 0.8em;
  margin-bottom: 2em;
}

.second-body {
  font-family: 'Poppins', sans-serif;
  padding-left: 10em;
  padding-right: 10em;
  color: slategray;
}

.main-heading {
  font-size: 3em;
  color: slategrey;
}

.body-text {
  font-size: 1.0em;
}

.job-list {
  font-size: 1.0em;
}

.main-body {
  background-color: ivory;
  min-height: 400px;
  margin-bottom: 100px;
  clear: both;
}

.question {
  font-size: 1.7em;
  font-weight: bolder;
}

.answer {
  font-size: 1em;
}

.footer-bottom {
  background: #343a40;
  color: #686868;
  height: 50px;
  text-align: center;
  position: absolute;
  bottom: 0px;
  left: 0px;
  padding-top: 20px;
}
<head>
  <title>Cleaning by Mark</title>
  <meta name = "viewport" content = "width=device-width, initial scale=1">
  <link rel = "preconnect" href = "https://fonts.googleapis.com">
  <link rel = "preconnect" href = "https://fonts.gstatic.com" crossorigin>
  <link href = "https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel = "stylesheet">
  <link rel = "preconnect" href = "https://fonts.googleapis.com">
  <link rel = "preconnect" href = "https://fonts.gstatic.com" crossorigin>
  <link href = "https://fonts.googleapis.com/css2?family=DM+Sans&display=swap" rel = "stylesheet">
  <link href = "styles.css" rel = "stylesheet">
</head>
<body class = "main-body">
  <nav class=nav-bar>
    <span style = "font-size: 1.5em; font-weight: bold; color: slategray;">Commercial Cleaning</span>
    <a href = "index.html">HOME</a>
    <a href = "faq.html">FAQ</a>
    <a href = "contact.html">CONTACT</a>
    <a href = "gallery.html">GALLERY</a>
  </nav>
  <div class = "second-body">
    <div class = "row">
      <div class = "left-column">
        <h1 class = "main-heading">FAQ</h1>
        <h2>Some frequently asked questions with answers:</h2>
        <br>
        <br>
        <h2 class = "question">What services do you provide?</h2>
        <h3 class = "answer">A whole range of services is on offer, from patio and driveway cleaning to roof and conservatory cleaning! Feel free to check out the services offered on the 'Home' page. If you still have a question, or would like to enquire about another service,
          feel free to access the 'Contact' page and get in touch any time.</h3>
        <h2 class = "question">What are your prices?</h2>
        <h3 class = "answer">It's always difficult to provide an accurate quote without first assessing the job. However, Mark will happily provide a free no obligation quote - you may be surprised!</h5>
          <br>
          <h2 class = "question">Are you able to clean rooves on houses?</h2>
          <h3 class = "answer">Yes! Mark's reach isn't limited to bungalows, conservatories and annexes. With his state-of-the-art equipment, he will be able to clean all the moss and dirt from house rooves too!</h5>
            <h2 class = "question">Do I need to provide anything?</h2>
            <h3 class = "answer">Here at Commercial Cleaning, we will provide all tools and chemicals required to clean the job. However, there may need to be an access for water - this is more possible with larger jobs. But rest assured, there will be no cost to you - the
              cost of water will be deducted from your final invoice!</h3>
      </div>
      <div class = "right-column" id = "right-col-home">
      </div>
    </div>
  </div>
  <!-- Footer -->
  <div class = "footer-bottom">
    &copy; 2022 | commercialcleaning.com | Designed by Kieran|
  </div>
</body>

Заранее спасибо.

Из кода я понимаю, что нижний колонтитул </div> не имеет начального тега. Он находится над тегом body. Я думаю, вы должны попробовать добавить начальный тег <div> ниже строки комментария нижнего колонтитула.

Omkar Pattanaik 14.09.2022 20:31

Ах, да, похоже, это лишняя строка нежелательного кода, которую я забыл удалить; это было из тега <div>, который существовал, но больше не существует! Спасибо, что указали мне на это, я сейчас исправил это.

Kieran Hovell 14.09.2022 20:34

К вашему сведению, теги — это просто текст в файле. Элементы — это то, что вы видите в браузере, и для их отображения часто требуются два тега.

isherwood 14.09.2022 21:03
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Введение в CSS
Введение в CSS
CSS является неотъемлемой частью трех основных составляющих front-end веб-разработки.
Как выровнять Div по центру?
Как выровнять Div по центру?
Чтобы выровнять элемент <div>по горизонтали и вертикали с помощью CSS, можно использовать комбинацию свойств и значений CSS. Вот несколько методов,...
Навигация по приложениям React: Исчерпывающее руководство по React Router
Навигация по приложениям React: Исчерпывающее руководство по React Router
React Router стала незаменимой библиотекой для создания одностраничных приложений с навигацией в React. В этой статье блога мы подробно рассмотрим...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
Toor - Ангулярный шаблон для бронирования путешествий
Toor - Ангулярный шаблон для бронирования путешествий
Toor - Travel Booking Angular Template один из лучших Travel & Tour booking template in the world. 30+ валидированных HTML5 страниц, которые помогут...
2
3
100
4
Перейти к ответу Данный вопрос помечен как решенный

Ответы 4

Попробуйте добавить overflow-y:hidden; в класс .footer-bottom. Это довольно просто — предотвратит переполнение страницы по вертикальной оси.

Обновлено:
Если это не поможет, вы можете использовать теги разделов и дополнить их (что будет вашим лучшим вариантом).
то есть)

<section title = "Section1">
<!-- Apply padding to top and bottom of Section1 in CSS. -->
Content here
</section>
<section title = "Footer">
<!-- Apply padding to top of Footer in CSS. -->
Content here
</section>

Надеюсь это поможет. Ваше здоровье!

Большое спасибо за быстрый ответ, однако это, похоже, не исправило это. Он по-прежнему остается внизу страницы, хотя и закрывает контент, а не прокручивается вниз вместе с остальной частью тела.

Kieran Hovell 14.09.2022 20:31

Приносим извинения — пожалуйста, прочитайте обновление.

Hydro 14.09.2022 20:34

Я еще не экспериментировал с тегом section, но обязательно попробую после некоторых исследований. Спасибо за предложение! Я сделал комментарий в своем исходном коде, чтобы он работал как можно скорее.

Kieran Hovell 14.09.2022 20:39

На первый взгляд кажется, что ваш нижний колонтитул настроен на «абсолютную» позицию. Когда вы делаете это, он не принимает во внимание ничего, что может быть скрыто за этим.

Я обычно исправляю это, добавляя больше поля к содержимому позади него — в этом случае это будет дополнительное поле внизу.

Таким образом, скрытое содержимое будет иметь дополнительное пространство для прокрутки вниз, таким образом делая скрытое содержимое видимым (над нижним колонтитулом).

Обновлено: я думаю, что описывал проблему, которая на самом деле не была вашей проблемой.

Вы можете сделать «position: fixed», если хотите, чтобы нижний колонтитул был зафиксирован на месте, даже с помощью прокрутки (если вы хотите это сделать).

Если вы хотите продолжить с «абсолютной» позицией, обратите внимание, что точка отсчета «нижняя часть: 0» зависит от родительского контейнера, который, как я думаю, в данном случае является телом. Если контейнер имеет «позиция: относительная» (например, если он находится внутри div, для которого вы указали относительное положение), то он займет нижнюю часть этого div.

Поэтому, если ваш нижний колонтитул перемещается нежелательным образом при прокрутке, это связано с тем, что он привязан к нижней части родителя/контейнера (которое является position: relative). Таким образом, вы должны обратиться к родителю - если вы хотите, чтобы нижний колонтитул всегда находился внизу страницы, то якорь/родитель нижнего колонтитула должен быть внизу документа.

Надеюсь, эта информация окажется полезной!

Извините за поздний ответ, но большое спасибо за подробное описание свойства position и его значений! Это помогло мне лучше их понять, а также лучше понять, что пошло не так. Благодаря вашей информации и ответу Кэмерона я теперь в состоянии правильно разобраться в нижнем колонтитуле и продолжить обучение. Большое спасибо!

Kieran Hovell 14.09.2022 21:31
Ответ принят как подходящий

Удалите свои единицы vh, в данном случае это проблематично, потому что на небольших устройствах избыточный текст может превышать установленный vh и «вытекать» под footer.

Затем измените footer на position: relative; и установите min-height: 100%; на .second-body.

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

nav a {
  color: black;
  font-family: 'DM Sans', sans-serif;
  font-size: 1.2em;
  padding: 12px;
  text-decoration: none;
  width: 80%;
  text-align: center;
  padding-left: 5em;
  padding-right: 2em;
}

.row {
  display: flex;
}

.left-column {
  height: 100%;
  flex: 50%;
}

.right-column {
  flex: 50%;
  background-position: center;
  background-size: contain;
  background-repeat: no-repeat;
}

#right-col-home {
  background-image: url(https://s3.amazonaws.com/bprblogassets/blog/wp-content/uploads/2017/06/11165212/Power-Washing-Beginner.png);
}

.nav-bar {
  border-width: 0em;
  border-color: ghostwhite;
  border-bottom: 0.15em solid gray;
  font-family: 'Poppins', sans-serif;
  background-color: ghostwhite;
  overflow: auto;
  padding: 0.8em;
  margin-bottom: 2em;
}

.second-body {
  font-family: 'Poppins', sans-serif;
  padding-left: 5em;
  padding-right: 5em;
  color: slategray;
  display: flex;
  min-height: 100%;
}

.main-heading {
  font-size: 3em;
  color: slategrey;
}

.body-text {
  font-size: 1.0em;
}

.job-list {
  font-size: 1.0em;
}

.main-body {
  background-color: ivory;
  min-height: 400px;
  margin-bottom: 100px;
  clear: both;
}

.question {
  font-size: 1.7em;
  font-weight: bolder;
}

.answer {
  font-size: 1em;
}

.footer-bottom {
  background: #343a40;
  color: #686868;
  padding: 25px 0;
  text-align: center;
  position: relative;
  bottom: 0px;
  left: 0px;
  padding-top: 20px;
}
<!DOCTYPE html>
<html>

<head>
  <title>Cleaning by Mark</title>
  <meta name = "viewport" content = "width=device-width, initial scale=1">
  <link rel = "preconnect" href = "https://fonts.googleapis.com">
  <link rel = "preconnect" href = "https://fonts.gstatic.com" crossorigin>
  <link href = "https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel = "stylesheet">
  <link rel = "preconnect" href = "https://fonts.googleapis.com">
  <link rel = "preconnect" href = "https://fonts.gstatic.com" crossorigin>
  <link href = "https://fonts.googleapis.com/css2?family=DM+Sans&display=swap" rel = "stylesheet">
  <link href = "styles.css" rel = "stylesheet">
</head>

<body class = "main-body">
  <nav class=nav-bar>
    <span style = "font-size: 1.5em; font-weight: bold; color: slategray;">Commercial Cleaning</span>
    <a href = "index.html">HOME</a>
    <a href = "faq.html">FAQ</a>
    <a href = "contact.html">CONTACT</a>
    <a href = "gallery.html">GALLERY</a>
  </nav>
  <div class = "second-body">
    <div class = "row">
      <div class = "left-column">
        <h1 class = "main-heading">FAQ</h1>
        <h2>Some frequently asked questions with answers:</h2>
        <br>
        <br>
        <h2 class = "question">What services do you provide?</h2>
        <h3 class = "answer">A whole range of services is on offer, from patio and driveway cleaning to roof and conservatory cleaning! Feel free to check out the services offered on the 'Home' page. If you still have a question, or would like to enquire about another service,
          feel free to access the 'Contact' page and get in touch any time.</h3>
        <h2 class = "question">What are your prices?</h2>
        <h3 class = "answer">It's always difficult to provide an accurate quote without first assessing the job. However, Mark will happily provide a free no obligation quote - you may be surprised!</h5>
          <br>
          <h2 class = "question">Are you able to clean rooves on houses?</h2>
          <h3 class = "answer">Yes! Mark's reach isn't limited to bungalows, conservatories and annexes. With his state-of-the-art equipment, he will be able to clean all the moss and dirt from house rooves too!</h5>
            <h2 class = "question">Do I need to provide anything?</h2>
            <h3 class = "answer">Here at Commercial Cleaning, we will provide all tools and chemicals required to clean the job. However, there may need to be an access for water - this is more possible with larger jobs. But rest assured, there will be no cost to you - the
              cost of water will be deducted from your final invoice!</h3>
      </div>
      <div class = "right-column" id = "right-col-home"></div>
    </div>
  </div>
  <!-- Footer -->
  <div class = "footer-bottom">
    &copy; 2022 | commercialcleaning.com | Designed by Kieran|
  </div>
</body>

Большое спасибо, это полностью решило мою проблему. Мне любопытно, насколько проблематичны единицы vh, если у вас есть время, чтобы быстро ответить? В любом случае, мой нижний колонтитул теперь привязан к нижней части страницы, не закрывая содержание, и сегодня я узнал кое-что новое. Беспроигрышный вариант!

Kieran Hovell 14.09.2022 20:49

@KieranHovell vh в этом случае проблематичен, потому что у вас есть много текстового контента на одной стороне, который имеет height: 40vh;, а это означает, что когда вы уменьшаете высоту браузера (под 40vh), контент попадает под footer, потому что он поддерживает 40vh, что он не имеет места, например, когда вы запускаете фрагмент, не делая его на всю страницу ~ > 40vh. как на этом изображении

Kameron 14.09.2022 20:56

Ах, это имеет смысл, и я полностью понимаю; ошибку, которую я точно больше не совершу. Еще раз спасибо за ваше время и решение, которое вы предоставили.

Kieran Hovell 14.09.2022 20:57

Я добавил теги div к части. затем создал нижний колонтитул с другими настройками таблицы стилей. Я также добавил ссылку на стиль на html-страницу, но только для облегчения доступа к ней. Новые настройки нижнего колонтитула в части стиля называются #aFooter. Это удерживает нижний колонтитул внизу страницы, но не прокручивается. Возможно, стоит посмотреть на скрипт, чтобы тег div нижнего колонтитула был привязан к нижней части элемента окна веб-страницы.

            <!DOCTYPE html>
        <html>
            <head>
                <title>Cleaning by Mark</title>
                <meta name = "viewport" content = "width=device-width, initial scale=1">
                <link rel = "preconnect" href = "https://fonts.googleapis.com">
                <link rel = "preconnect" href = "https://fonts.gstatic.com" crossorigin>
                <link href = "https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel = "stylesheet">
                <link rel = "preconnect" href = "https://fonts.googleapis.com">
                <link rel = "preconnect" href = "https://fonts.gstatic.com" crossorigin>
                <link href = "https://fonts.googleapis.com/css2?family=DM+Sans&display=swap" rel = "stylesheet">
                <link href = "styles.css" rel = "stylesheet">
            </head>
            
            <style>
        nav a {
            color: black;
            font-family: 'DM Sans', sans-serif;
            font-size: 1.2em;
            padding: 12px;
            text-decoration: none;
            width: 80%;
            text-align: center;
            padding-left: 5em;
            padding-right: 2em;
        }
        .row{
            display: flex;
        }
        .left-column {
            height: 80vh; 
            flex: 50%;
        }
        .right-column {
            height: 35vh;
            flex: 50%;
            background-position: right; 
            background-size: contain;
            background-repeat: no-repeat;
        }
        #right-col-home {
            background-image: url(https://s3.amazonaws.com/bprblogassets/blog/wp-content/uploads/2017/06/11165212/Power-Washing-Beginner.png);
            margin-top: 12em;
        }
        .nav-bar {
            border-width: 0em;
            border-color: ghostwhite;
            border-bottom: 0.15em solid gray;
            font-family: 'Poppins', sans-serif;
            background-color: ghostwhite;
            overflow: auto;
            padding: 0.8em;
            margin-bottom: 2em;
        }
        .second-body {
            font-family: 'Poppins', sans-serif;
            padding-left: 10em;
            padding-right: 10em;
            color:slategray;
        }
        .main-heading {
            font-size: 3em;
            color: slategrey;
        }
        .body-text {
            font-size: 1.0em;
        }
        .job-list {
            font-size: 1.0em;
        }
        .main-body {
            background-color: ivory;
            min-height: 400px;
            margin-bottom: 100px;
            clear: both;
        }
        .question {
            font-size: 1.7em;
            font-weight: bolder;
        }
        .answer {
            font-size: 1em;
        }
        .footer-bottom {
            background: #343a40;
            color: #686868;
            height: 50px;
            text-align: center;
            position:relative;
                bottom: 0px;
                left: 0px;
            padding-top: 20px;
        }
        
            #aFooter {
        position: relative;
        min-height: 150px;
                bottom: 0px;
                left: 0px;
        }
        
        #aFooter-content {
        position: absolute;
        bottom: 0;
        left: 0;
        }
        
        #aFooter, #aFooter * {
        background: #343a40;
        }
        </style>    
            
        
            
            <body class = "main-body">
            <div>
                <nav class=nav-bar>
                    <span style = "font-size: 1.5em; font-weight: bold; color: slategray;">Commercial Cleaning</span>
                    <a href = "index.html">HOME</a>
                    <a href = "faq.html">FAQ</a>
                    <a href = "contact.html">CONTACT</a>
                    <a href = "gallery.html">GALLERY</a>
                </nav>
            
                
                
                <div class = "second-body">
                
                    <div class = "row">
                
                        <div class = "left-column">
                            <h1 class = "main-heading">FAQ</h1>
                            <h2>Some frequently asked questions with answers:</h2>
                            <br>
                            <br>
                            <h2 class = "question">What services do you provide?</h2>
                            <h3 class = "answer">A whole range of services is on offer, from patio and driveway cleaning to roof and conservatory cleaning!  Feel free to check out the services offered on the 'Home' page.  If you still have a question, or would like to enquire about another service, feel free to access the 'Contact' page and get in touch any time.</h3>
                            <h2 class = "question">What are your prices?</h2>
                            <h3 class = "answer">It's always difficult to provide an accurate quote without first assessing the job.  However, Mark will happily provide a free no obligation quote - you may be surprised!</h5>
                            <br>
                            <h2 class = "question">Are you able to clean rooves on houses?</h2>
                            <h3 class = "answer">Yes!  Mark's reach isn't limited to bungalows, conservatories and annexes.  With his state-of-the-art equipment, he will be able to clean all the moss and dirt from house rooves too!</h5>
                            <h2 class = "question">Do I need to provide anything?</h2>
                            <h3 class = "answer">Here at Commercial Cleaning, we will provide all tools and chemicals required to clean the job.  However, there may need to be an access for water - this is more possible with larger jobs.  But rest assured, there will be no cost to you - the cost of water will be deducted from your final invoice!</h3>
                    <BR><BR> <br> <br> <br><br> <BR>
                    <BR><br><br> <br><br><BR><br><br> <br><br>
        
        
                    </div>
        
                    
                    </div>
                    
                    <div class = "right-column" id = "right-col-home">
                    This is right column.
                            </div>          
                </div>  
            </div>
            <div id = "aFooter">
        <center> <h1>Footer</h1>
        <div id = "header-content">   &copy; 2022 | commercialcleaning.com | Designed by Kieran| </div>
        <center>
        </div>
            
            </body>

Другие вопросы по теме