Как добавить скролл на страницу html
Перейти к содержимому

Как добавить скролл на страницу html

  • автор:

Getting started with HTML

In this article, we cover the absolute basics of HTML. To get you started, this article defines elements, attributes, and all the other important terms you may have heard. It also explains where these fit into HTML. You will learn how HTML elements are structured, how a typical HTML page is structured, and other important basic language features. Along the way, there will be an opportunity to play with HTML too!

Prerequisites: Basic software installed, and basic knowledge of working with files.
Objective: To gain basic familiarity with HTML, and practice writing a few HTML elements.

What is HTML?

HTML (HyperText Markup Language) is a markup language that tells web browsers how to structure the web pages you visit. It can be as complicated or as simple as the web developer wants it to be. HTML consists of a series of elements, which you use to enclose, wrap, or mark up different parts of content to make it appear or act in a certain way. The enclosing tags can make content into a hyperlink to connect to another page, italicize words, and so on. For example, consider the following line of text:

My cat is very grumpy

If we wanted the text to stand by itself, we could specify that it is a paragraph by enclosing it in a paragraph ( ) element:

p>My cat is very grumpyp> 

Anatomy of an HTML element

Let’s further explore our paragraph element from the previous section:

The anatomy of our element is:

  • The opening tag: This consists of the name of the element (in this example, p for paragraph), wrapped in opening and closing angle brackets. This opening tag marks where the element begins or starts to take effect. In this example, it precedes the start of the paragraph text.
  • The content: This is the content of the element. In this example, it is the paragraph text.
  • The closing tag: This is the same as the opening tag, except that it includes a forward slash before the element name. This marks where the element ends. Failing to include a closing tag is a common beginner error that can produce peculiar results.

The element is the opening tag, followed by content, followed by the closing tag.

Active learning: creating your first HTML element

Edit the line below in the «Editable code» area by wrapping it with the tags and . To open the element, put the opening tag at the start of the line. To close the element, put the closing tag at the end of the line. Doing this should give the line italic text formatting! See your changes update live in the Output area.

If you make a mistake, you can clear your work using the Reset button. If you get really stuck, press the Show solution button to see the answer.

h2>Live outputh2> div class="output" style="min-height: 50px;">div> h2>Editable codeh2> p class="a11y-label"> Press Esc to move focus away from the code area (Tab inserts a tab character). p> textarea id="code" class="playable-code" style="min-height: 100px;width: 95%"> This is my text. textarea> div class="controls"> input id="reset" type="button" value="Reset" /> input id="solution" type="button" value="Show solution" /> div> 
html  font-family: "Open Sans Light", Helvetica, Arial, sans-serif; > h2  font-size: 16px; > .a11y-label  margin: 0; text-align: right; font-size: 0.7rem; width: 98%; > body  margin: 10px; background: #f5f9fa; > 
const textarea = document.getElementById("code"); const reset = document.getElementById("reset"); const solution = document.getElementById("solution"); const output = document.querySelector(".output"); const code = textarea.value; let userEntry = textarea.value; function updateCode()  output.innerHTML = textarea.value; > const htmlSolution = "This is my text."; let solutionEntry = htmlSolution; reset.addEventListener("click", () =>  textarea.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = "Show solution"; updateCode(); >); solution.addEventListener("click", () =>  if (solution.value === "Show solution")  textarea.value = solutionEntry; solution.value = "Hide solution"; > else  textarea.value = userEntry; solution.value = "Show solution"; > updateCode(); >); textarea.addEventListener("input", updateCode); window.addEventListener("load", updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = (e) =>  if (e.keyCode === 9)  e.preventDefault(); insertAtCaret("\t"); > if (e.keyCode === 27)  textarea.blur(); > >; function insertAtCaret(text)  const scrollPos = textarea.scrollTop; let caretPos = textarea.selectionStart; const front = textarea.value.substring(0, caretPos); const back = textarea.value.substring( textarea.selectionEnd, textarea.value.length, ); textarea.value = front + text + back; caretPos += text.length; textarea.selectionStart = caretPos; textarea.selectionEnd = caretPos; textarea.focus(); textarea.scrollTop = scrollPos; > // Update the saved userCode every time the user updates the text area code textarea.onkeyup = () =>  // We only want to save the state when the user code is being shown, // not the solution, so that solution is not saved over the user code if (solution.value === "Show solution")  userEntry = textarea.value; > else  solutionEntry = textarea.value; > updateCode(); >; 

Nesting elements

Elements can be placed within other elements. This is called nesting. If we wanted to state that our cat is very grumpy, we could wrap the word very in a element, which means that the word is to have strong(er) text formatting:

p>My cat is strong>verystrong> grumpy.p> 

There is a right and wrong way to do nesting. In the example above, we opened the p element first, then opened the strong element. For proper nesting, we should close the strong element first, before closing the p .

The following is an example of the wrong way to do nesting:

p>My cat is strong>very grumpy.p>strong> 

The tags have to open and close in a way that they are inside or outside one another. With the kind of overlap in the example above, the browser has to guess at your intent. This kind of guessing can result in unexpected results.

Void elements

Not all elements follow the pattern of an opening tag, content, and a closing tag. Some elements consist of a single tag, which is typically used to insert/embed something in the document. Such elements are called void elements. For example, the element embeds an image file onto a page:

img src="https://raw.githubusercontent.com/mdn/beginner-html-site/gh-pages/images/firefox-icon.png" alt="Firefox icon" /> 

This would output the following:

cat

Note: In HTML, there is no requirement to add a / at the end of a void element’s tag, for example: . However, it is also a valid syntax, and you may do this when you want your HTML to be valid XML.

Attributes

Elements can also have attributes. Attributes look like this:

paragraph tag with

Attributes contain extra information about the element that won’t appear in the content. In this example, the class attribute is an identifying name used to target the element with style information.

An attribute should have:

  • A space between it and the element name. (For an element with more than one attribute, the attributes should be separated by spaces too.)
  • The attribute name, followed by an equal sign.
  • An attribute value, wrapped with opening and closing quote marks.

Active learning: Adding attributes to an element

The element can take a number of attributes, including:

The src attribute is a required attribute that specifies the location of the image. For example: src=»https://raw.githubusercontent.com/mdn/beginner-html-site/gh-pages/images/firefox-icon.png» .

The alt attribute specifies a text description of the image. For example: alt=»The Firefox icon» .

The width attribute specifies the width of the image with the unit being pixels. For example: width=»300″ .

The height attribute specifies the height of the image with the unit being pixels. For example: height=»300″ .

Edit the line below in the Input area to turn it into an image.

  1. Find your favorite image online, right click it, and press Copy Image Link/Address.
  2. Back in the area below, add the src attribute and fill it with the link from step 1.
  3. Set the alt attribute.
  4. Add the width and height attributes.

You will be able to see your changes live in the Output area.

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

h2>Live outputh2> div class="output" style="min-height: 50px;">div> h2>Editable codeh2> p class="a11y-label"> Press Esc to move focus away from the code area (Tab inserts a tab character). p> textarea id="code" class="input" style="min-height: 100px;width: 95%"> <img alt="I should be an image" > textarea> div class="playable-buttons"> input id="reset" type="button" value="Reset" /> input id="solution" type="button" value="Show solution" /> div> 
html  font-family: sans-serif; > h2  font-size: 16px; > .a11y-label  margin: 0; text-align: right; font-size: 0.7rem; width: 98%; > body  margin: 10px; background: #f5f9fa; > 
const textarea = document.getElementById("code"); const reset = document.getElementById("reset"); const solution = document.getElementById("solution"); const output = document.querySelector(".output"); const code = textarea.value; let userEntry = textarea.value; function updateCode()  output.innerHTML = textarea.value; > const htmlSolution = ' '; let solutionEntry = htmlSolution; reset.addEventListener("click", () =>  textarea.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = "Show solution"; updateCode(); >); solution.addEventListener("click", () =>  if (solution.value === "Show solution")  textarea.value = solutionEntry; solution.value = "Hide solution"; > else  textarea.value = userEntry; solution.value = "Show solution"; > updateCode(); >); textarea.addEventListener("input", updateCode); window.addEventListener("load", updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = (e) =>  if (e.keyCode === 9)  e.preventDefault(); insertAtCaret("\t"); > if (e.keyCode === 27)  textarea.blur(); > >; function insertAtCaret(text)  const scrollPos = textarea.scrollTop; let caretPos = textarea.selectionStart; const front = textarea.value.substring(0, caretPos); const back = textarea.value.substring( textarea.selectionEnd, textarea.value.length, ); textarea.value = front + text + back; caretPos += text.length; textarea.selectionStart = caretPos; textarea.selectionEnd = caretPos; textarea.focus(); textarea.scrollTop = scrollPos; > // Update the saved userCode every time the user updates the text area code textarea.onkeyup = () =>  // We only want to save the state when the user code is being shown, // not the solution, so that solution is not saved over the user code if (solution.value === "Show solution")  userEntry = textarea.value; > else  solutionEntry = textarea.value; > updateCode(); >; 

Boolean attributes

Sometimes you will see attributes written without values. This is entirely acceptable. These are called Boolean attributes. Boolean attributes can only have one value, which is generally the same as the attribute name. For example, consider the disabled attribute, which you can assign to form input elements. (You use this to disable the form input elements so the user can’t make entries. The disabled elements typically have a grayed-out appearance.) For example:

input type="text" disabled="disabled" /> 

As shorthand, it is acceptable to write this as follows:

input type="text" disabled /> input type="text" /> 

For reference, the example above also includes a non-disabled form input element. The HTML from the example above produces this result:

Omitting quotes around attribute values

If you look at code for a lot of other sites, you might come across a number of strange markup styles, including attribute values without quotes. This is permitted in certain circumstances, but it can also break your markup in other circumstances. The element in the code snippet below, , is called an anchor. Anchors enclose text and turn them into links. The href attribute specifies the web address the link points to. You can write this basic version below with only the href attribute, like this:

a href=https://www.mozilla.org/>favorite websitea> 

Anchors can also have a title attribute, a description of the linked page. However, as soon as we add the title in the same fashion as the href attribute there are problems:

a href=https://www.mozilla.org/ title=The Mozilla homepage>favorite websitea> 

As written above, the browser misinterprets the markup, mistaking the title attribute for three attributes: a title attribute with the value The , and two Boolean attributes, Mozilla and homepage . Obviously, this is not intended! It will cause errors or unexpected behavior, as you can see in the live example below. Try hovering over the link to view the title text!

Always include the attribute quotes. It avoids such problems, and results in more readable code.

Single or double quotes?

In this article, you will also notice that the attributes are wrapped in double quotes. However, you might see single quotes in some HTML code. This is a matter of style. You can feel free to choose which one you prefer. Both of these lines are equivalent:

a href='https://www.example.com'>A link to my example.a> a href="https://www.example.com">A link to my example.a> 

Make sure you don’t mix single quotes and double quotes. This example (below) shows a kind of mixing of quotes that will go wrong:

However, if you use one type of quote, you can include the other type of quote inside your attribute values:

a href="https://www.example.com" title="Isn't this fun?"> A link to my example. a> 

To use quote marks inside other quote marks of the same type (single quote or double quote), use HTML entities. For example, this will break:

a href="https://www.example.com" title="An "interesting" reference">A link to my example.a> 

Instead, you need to do this:

a href="https://www.example.com" title="An "interesting" reference">A link to my example.a> 

Anatomy of an HTML document

Individual HTML elements aren’t very useful on their own. Next, let’s examine how individual elements combine to form an entire HTML page:

doctype html> html lang="en-US"> head> meta charset="utf-8" /> title>My test pagetitle> head> body> p>This is my pagep> body> html> 

    : The doctype. When HTML was young (1991-1992), doctypes were meant to act as links to a set of rules that the HTML page had to follow to be considered good HTML. Doctypes used to look something like this:

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

Active learning: Adding some features to an HTML document

If you want to experiment with writing some HTML on your local computer, you can:

  1. Copy the HTML page example listed above.
  2. Create a new file in your text editor.
  3. Paste the code into the new text file.
  4. Save the file as index.html .

Note: You can also find this basic HTML template on the MDN Learning Area GitHub repo.

You can now open this file in a web browser to see what the rendered code looks like. Edit the code and refresh the browser to see what the result is. Initially, the page looks like this:

A simple HTML page that says This is my page

In this exercise, you can edit the code locally on your computer, as described previously, or you can edit it in the sample window below (the editable sample window represents just the contents of the element, in this case). Sharpen your skills by implementing the following tasks:

  • Just below the opening tag of the element, add a main title for the document. This should be wrapped inside an

    opening tag and

    closing tag.

  • Edit the paragraph content to include text about a topic that you find interesting.
  • Make important words stand out in bold by wrapping them inside a opening tag and closing tag.
  • Add a link to your paragraph, as explained earlier in the article.
  • Add an image to your document. Place it below the paragraph, as explained earlier in the article. Earn bonus points if you manage to link to a different image (either locally on your computer or somewhere else on the web).

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

h2>Live outputh2> div class="output" style="min-height: 50px;">div> h2>Editable codeh2> p class="a11y-label"> Press Esc to move focus away from the code area (Tab inserts a tab character). p> textarea id="code" class="input" style="min-height: 100px;width: 95%"> <p>This is my page</p> textarea> div class="playable-buttons"> input id="reset" type="button" value="Reset" /> input id="solution" type="button" value="Show solution" /> div> 
html  font-family: sans-serif; > h1  color: blue; > h2  font-size: 16px; > .a11y-label  margin: 0; text-align: right; font-size: 0.7rem; width: 98%; > img  max-width: 100%; > body  margin: 10px; background: #f5f9fa; > 
const textarea = document.getElementById("code"); const reset = document.getElementById("reset"); const solution = document.getElementById("solution"); const output = document.querySelector(".output"); const code = textarea.value; let userEntry = textarea.value; function updateCode()  output.innerHTML = textarea.value; > const htmlSolution = '

Some music

I really enjoy playing the drums. One of my favorite drummers is Neal Peart, who plays in the band Rush. My favorite Rush album is currently Moving Pictures.

Rush Moving Pictures album cover'
; let solutionEntry = htmlSolution; reset.addEventListener("click", () => textarea.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = "Show solution"; updateCode(); >); solution.addEventListener("click", () => if (solution.value === "Show solution") textarea.value = solutionEntry; solution.value = "Hide solution"; > else textarea.value = userEntry; solution.value = "Show solution"; > updateCode(); >); textarea.addEventListener("input", updateCode); window.addEventListener("load", updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = (e) => if (e.keyCode === 9) e.preventDefault(); insertAtCaret("\t"); > if (e.keyCode === 27) textarea.blur(); > >; function insertAtCaret(text) const scrollPos = textarea.scrollTop; let caretPos = textarea.selectionStart; const front = textarea.value.substring(0, caretPos); const back = textarea.value.substring( textarea.selectionEnd, textarea.value.length, ); textarea.value = front + text + back; caretPos += text.length; textarea.selectionStart = caretPos; textarea.selectionEnd = caretPos; textarea.focus(); textarea.scrollTop = scrollPos; > // Update the saved userCode every time the user updates the text area code textarea.onkeyup = () => // We only want to save the state when the user code is being shown, // not the solution, so that solution is not saved over the user code if (solution.value === "Show solution") userEntry = textarea.value; > else solutionEntry = textarea.value; > updateCode(); >;

Whitespace in HTML

In the examples above, you may have noticed that a lot of whitespace is included in the code. This is optional. These two code snippets are equivalent:

p id="noWhitespace">Dogs are silly.p> p id="whitespace">Dogs are silly.p> 

No matter how much whitespace you use inside HTML element content (which can include one or more space characters, but also line breaks), the HTML parser reduces each sequence of whitespace to a single space when rendering the code. So why use so much whitespace? The answer is readability.

It can be easier to understand what is going on in your code if you have it nicely formatted. In our HTML we’ve got each nested element indented by two spaces more than the one it is sitting inside. It is up to you to choose the style of formatting (how many spaces for each level of indentation, for example), but you should consider formatting it.

Let’s have a look at how the browser renders the two paragraphs above with and without whitespace:

Note: Accessing the innerHTML of elements from JavaScript will keep all the whitespace intact. This may return unexpected results if the whitespace is trimmed by the browser.

const noWhitespace = document.getElementById("noWhitespace").innerHTML; console.log(noWhitespace); // "Dogs are silly." const whitespace = document.getElementById("whitespace").innerHTML; console.log(whitespace); // "Dogs // are // silly." 

Entity references: Including special characters in HTML

In HTML, the characters < , >, » , ‘ , and & are special characters. They are parts of the HTML syntax itself. So how do you include one of these special characters in your text? For example, if you want to use an ampersand or less-than sign, and not have it interpreted as code.

You do this with character references. These are special codes that represent characters, to be used in these exact circumstances. Each character reference starts with an ampersand (&), and ends with a semicolon (;).

Literal character Character reference equivalent
<
> >
« "
'
& &

The character reference equivalent could be easily remembered because the text it uses can be seen as less than for < , quotation for " and similarly for others. To find more about entity references, see List of XML and HTML character entity references (Wikipedia).

In the example below, there are two paragraphs:

p>In HTML, you define a paragraph using the p> element.p> p>In HTML, you define a paragraph using the <p> element.p> 

In the live output below, you can see that the first paragraph has gone wrong. The browser interprets the second instance of

as starting a new paragraph. The second paragraph looks fine because it has angle brackets with character references.

Note: You don’t need to use entity references for any other symbols, as modern browsers will handle the actual symbols just fine as long as your HTML’s character encoding is set to UTF-8.

HTML comments

HTML has a mechanism to write comments in the code. Browsers ignore comments, effectively making comments invisible to the user. The purpose of comments is to allow you to include notes in the code to explain your logic or coding. This is very useful if you return to a code base after being away for long enough that you don’t completely remember it. Likewise, comments are invaluable as different people are making changes and updates.

To write an HTML comment, wrap it in the special markers . For example:

p>I'm not inside a commentp> I am!

-->

As you can see below, only the first paragraph is displayed in the live output.

Summary

You made it to the end of the article! We hope you enjoyed your tour of the basics of HTML.

At this point, you should understand what HTML looks like, and how it works at a basic level. You should also be able to write a few elements and attributes. The subsequent articles of this module go further on some of the topics introduced here, as well as presenting other concepts of the language.

  • As you start to learn more about HTML, consider learning the basics of CSS (Cascading Style Sheets). CSS is the language used to style web pages, such as changing fonts or colors or altering the page layout. HTML and CSS work well together, as you will soon discover.

See also

  • Applying color to HTML elements using CSS
  • Overview: Introduction to HTML
  • Next

overflow

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

Синтаксис

overflow: auto | hidden | scroll | visible | inherit

Значения

visible Отображается все содержание элемента, даже за пределами установленной высоты и ширины. hidden Отображается только область внутри элемента, остальное будет скрыто. scroll Всегда добавляются полосы прокрутки. auto Полосы прокрутки добавляются только при необходимости. inherit Наследует значение родителя.

HTML5 CSS2.1 IE Cr Op Sa Fx

    overflow   
Duis te feugifacilisi

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat. Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Результат данного примера показан на рис. 1.

Применение свойства overflow

Рис. 1. Применение свойства overflow

Объектная модель

[window.]document.getElementById(» elementID «).style.overflow

Браузеры

Internet Explorer до версии 7.0 включительно:

  • не поддерживает значение inherit ;
  • относительно позиционированные дочерние элементы, значения overflow у которых заданы как auto или scroll ведут себя словно у них задано position : fixed .

Internet Explorer 8:

  • Сочетание overflow со значением scroll со свойствами max-height и float может привести к пропаданию элементов веб-страницы, в браузере выводится пустой экран.
  • Для блока, у которого указаны свойства float и overflow со значением scroll , игнорируется ширина, заданная через свойство max-width .
  • Высота блока с горизонтальной полосой прокрутки увеличивается на высоту скролбара, хотя по спецификации CSS заданные размеры должны включать в себя и полосы прокрутки.

как разместить скрол поверх контента, а не сбоку?

В браузеры не особо пекутся на счет лифтов. Это сам народ желает поизголяться на эту тему.

30 мая 2023 в 17:35

0

Сортировка: Сброс на вариант по умолчанию

Знаете кого-то, кто может ответить? Поделитесь ссылкой на этот вопрос по почте, через Твиттер или Facebook.

  • html
  • css
    Важное на Мете
Похожие

Подписаться на ленту

Лента вопроса

Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.

Дизайн сайта / логотип © 2024 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2024.4.30.8420

Прокручиваемый HTML-блок

Создаем блок с прокручиваемым текстом с помощью CSS и HTML

Создаем блок с прокручиваемым текстом с помощью CSS и HTML

Прокручиваемый HTML-блок — это блок, в котором, когда его содержимое больше размеров самого блока, справа и снизу появляются полосы прокрутки. Другими словами, если у вас есть блок, в котором может поместиться около 50 слов, и у вас есть текст, состоящий из 200 слов, в прокручиваемом HTML-блоке появятся полосы прокрутки, чтобы вы могли видеть остальные 150 слов. В стандартном HTML-блоке дополнительный текст просто выходит за его границы.

Создать прокручиваемый HTML-блок ( скролл для сайта ) довольно просто.

Вам просто нужно установить ширину и высоту элемента, а затем использовать свойство CSS overflow , чтобы указать поведение элемента, когда содержимое выходит за его пределы.

Что делать с дополнительным текстом?

Когда текста больше, чем может поместиться в доступное пространство макета, у вас есть несколько вариантов:

  • Перепишите текст, чтобы он стал короче.
  • Позвольте, чтобы текст выходил за пределы контейнера, и надейтесь, что макет может растягиваться, чтобы справиться с этой ситуацией.
  • Обрежьте текст там, где он выходит за пределы контейнера.
  • Добавьте полосы прокрутки (для текста — обычно вертикальные), чтобы с их помощью можно было просмотреть весь текст.

Лучшим вариантом, как правило, является последний: создать прокручиваемый текстовый блок. Тогда пользователь сможет прочитать весь текст, а макет останется без изменений.

HTML и CSS для этого :

здесь текст.

overflow: auto; указывает браузеру добавлять полосы прокрутки ( скролл ), если текст выходит за границы блока div .

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

Вы также можете обрезать текст, изменив значение свойства overflow с auto на hidden . Если вы не укажете свойство overflow , скролл на сайте работать не будет, и текст будет выходить за границы блока div .

Вы можете добавить полосы прокрутки не только для текста

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

Shasta playing frisbee

В этом примере изображение размером 400 на 509 пикселей размещено внутри абзаца, размер которого составляет 300 на 300 пикселей.

Полосы прокрутки могут использоваться в таблицах

Длинные таблицы могут быть очень трудными для восприятия, но, помещая их в блок div ограниченного размера, а затем, добавляя свойство overflow ( как способ сделать скролл ), можно создавать таблицы с большим количеством данных, которые не займут слишком много пространства на странице,

Самый простой способ сделать это — так же, как изображение и текст, просто оберните таблицу в блок div , установите его ширину и высоту и добавьте свойство overflow ( скролл внутри div ):

.
Name Phone
Jennifer 502-5366

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

Существует множество способов исправить это, например, изменение ширины таблицы и некоторые другие. Но я предпочитаю просто отключить горизонтальную прокрутку с помощью свойства CSS3 overflow-x . Просто укажите для блока div свойство overflow-x: hidden; , и горизонтальная полоса прокрутки будет удалена. Обязательно проверьте, чтобы одновременно с этим у вас не исчез и сам контент.

Firefox поддерживает использование overflow для тегов TBODY

Одна действительно приятная особенность браузера Firefox заключается в том, что вы можете использовать свойство overflow во внутренних тегах таблиц, таких как tbody и thead или tfoot . Это означает, что вы можете установить полосы прокрутки для содержимого таблицы, а ячейки заголовков останутся привязанными к ним.

Это работает только в Firefox , что не очень хорошо, но это полезная функция, если ваши читатели используют только Firefox . Посмотрите следующий пример, чтобы понять, что я имею в виду.

   Name Phone    Jennifer 502-5366  .

Вадим Дворников автор-переводчик статьи « HTML Scroll Box »

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *