Html горизонтальная прокрутка таблицы

Как сделать горизонтальную прокрутку таблицы на сайте

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

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

Создаем родительский блок с классом table-wrap , задаем ему максимальную ширину равную ширине таблицы, простую ширину делаем 100%, атрибут overflow ставим в auto.
Затем внутри него создаем таблицу с классом table и фиксированной шириной.

  
Вид услуги Ед. изм. Цена (руб.) Кол-во посещений
Консультация психолога Посещение от 2000 руб. 1
Консультация гастроэнтеролога Посещение от 5000 руб. 1
Вид услуги Ед. изм. Цена (руб.) Кол-во посещений
Консультация психолога Посещение от 2000 руб. 1
Консультация гастроэнтеролога Посещение от 5000 руб. 1

При ширине страницы 1000px и более прокрутки видно не будет, при уменьшении размера страницы по ширине, у таблицы появится горизонтальная прокрутка.
Настройка внешнего вида таблицы создается с помощью дополнительных стилей.
Как видите все просто, используйте этот способ в своих работах и создавайте качественный контент.

Источник

Как вместить большие таблицы на страницы сайта

Как вместить большие таблицы на страницы сайта

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

.big-table < overflow: auto; position: relative; >.big-table table < display: inline-block; vertical-align: top; max-width: 100%; overflow-x: auto; white-space: nowrap; -webkit-overflow-scrolling: touch; >.scroll-right:after < content: ''; display: block; width: 15px; position: absolute; top: 0; right: 0; bottom: 0; z-index: 500; background: radial-gradient(ellipse at right, rgba(0, 0, 0, 0.2) 0%, rgba(0, 0, 0, 0) 75%) 100% center; background-repeat: no-repeat; background-attachment: scroll; background-size: 15px 100%; background-position: 100% 0%; >.scroll-left:before

JQuery:

$(function() < $('table').wrap('box_width) < $(this).addClass('scroll-right'); >else < $(this).removeClass('scroll-right'); >>); > resize_table_box(); $( window ).on('resize', function() < resize_table_box(); >); $('.big-table table').on('scroll', function() < var parent = $(this).parent(); if ($(this).scrollLeft() + $(this).innerWidth() >= $(this)[0].scrollWidth) < if (parent.hasClass('scroll-right') )< parent.removeClass('scroll-right'); >> else if ($(this).scrollLeft() === 0) < if (parent.hasClass('scroll-left'))< parent.removeClass('scroll-left'); >> else < if(!parent.hasClass('scroll-right'))< parent.addClass('scroll-right'); >if(!parent.hasClass('scroll-left')) < parent.addClass('scroll-left'); >> >); >);

Результат:

Комментарии 2

Привет мастер! Совершенно случайно попал на эту страничку и обнаружил на ней скрипт моей мечты – очень давно хотел, чтобы таблица имела что-то позволяющее понять, что есть горизонтальная прокрутка таблицы. Попробовал применить ваш замечательный Код, однако столкнулся с проблемой. Если вся конструкция расположена непосредственно на странице со статьёй, то всё работает, но стоит вынести JS во внешний файл (на моём сайте много страниц с большими таблицами), перестаёт работать эффект тени. Как-то можно побороть эту неприятность?

Читайте также:  Вывести первую цифру числа python

Ничего не понимаю, почему это не работает здесь? https://re-news.com.ua/news/klassifikaczii-novostroek-kakie-byvayut-i-chem-otlichayutsya-2/

Авторизуйтесь, чтобы добавить комментарий.

Другие публикации

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

Источник

Making Tables Scrollable in CSS

Because HTML tables are set to display: table by default, adding scrollbars to them is a bit nonintuitive.

We can set our tables to display: block and modify their overflow from there, but I’ve found wrapping tables in containers to be more adaptable and flexible.

Vertical table scrollbars

First, let’s set up vertical scrolling.

div class="tableContainer"> table class="table"> . table> div> 

We can set a height for the table’s container and modify the table such that it will fit snug within the container:

.tableContainer < height: 300px; overflow: hidden; > .table < position: sticky; top: 0; width: 100%; > 

In this example, I set the height to 300px — but you can set it to whatever you want!

Our table will now have an inset vertical scrollbar and will expand no further than the height we set.

Horizontal table scrollbars

If you want to implement horizontal scrolling, there is an approach very similar to the vertical scrolling example:

.tableContainer < overflow: hidden; width: 800px; > .table < position: sticky; top: 0; width: 100%; > 

I set the width here to 800px , but again, you can change it to whatever you want.

If you want both horizontal and vertical scrollbars for your table, simply specify both a height and a width in .tableContainer .

And that’s how you can make your tables scrollable with just a bit of CSS!

I refer back to this snippet all the time, and I hope you found it useful too.

Источник

Table Scroll With HTML and CSS

When a user designs a database to manage employee data in a company, most of the data and records cannot fit into a single sheet or table. To manage the data, the user makes the sheet scrollable. There are two types of “scrollable”. The first is vertically scrollable, and the second is horizontally scrollable. Horizontal scrollable allows the user to scroll the contents of the window left or right. Whereas the vertical scrollbar allows the user to scroll up or down the content.

Method 1: How to Table Scroll Horizontally With HTML/CSS?

To make a table scroll horizontally with the HTML/CSS, first, design a table by utilizing the “ ” element. Then, set the “height” and “width” of the table in CSS and apply the “overflow” property with the value “scroll”.

Читайте также:  Найти сумму положительных нечетных чисел меньших 50 python

For practical implications, try the below-stated method.

Step 1: Add a div Container

For the purpose of creating a div container, add the “ ” element in the HTML document.

Step 2: Design a Table

Next, utilize the “ ” tag for designing a table to add data to the HTML page. Then, add the following attribute inside the table tag:

  • cellspacing” determines the space in the table cell.
  • cellpadding” specifies the space between the cell’s walls and the cell data. It is an inline attribute utilized in the table tag to overwrite the CSS style. The value of the cellpadding is set in pixels and can be specified as “1” or “0” by default.
  • border” is utilized for adding space around the cell.
  • Here, “width” defines the cell size in the table element.

Step 3: Add Data in Table

Next, add the following elements to add the data:

  • “ ” element is utilized for defining the rows in the table.
  • “ element determines a cell as the header of a group of table cells.
  • “ ” is used to add the data in the table:

It can be seen that the table has been added successfully:

Step 5: Style div Container

Access the div container by using the defined attribute value with the attribute selector. To do so, the “#main-content” is utilized in this scenario:

Then, apply these CSS properties:

  • border” is used for defining the boundary around the element.
  • margin” determines the space outside of the defined element.
  • padding” allocates space inside the defined boundary.

Output

Step 6: Make Table Horizontally Scrollable

Now, utilize the class name to access the table and apply the below-stated properties to make the table horizontally scrollable:

According to the given code:

  • height” and “width” properties are utilized for settings the size of the element.
  • overflow” controls what happens to content that is lengthy to fit into an area.

Output

Step 7: Style Table

For the purpose of styling the table, access the “table” and table data with “td”:

  • The “color” property is used for setting the color of the text in an element.
  • background” determines the color at the backside of the element.

Step 6: Style Table Heading

Access the table heading with the help of “th”:

Apply the “background-color” property to set the color at the element’s backside.

Method 2: How to Table Scroll Vertically With HTML/CSS?

To scroll the table vertically with the HTML/CSS, set the table width access the table with the help of the class name “.table-data” and apply the below-mentioned properties in the code snippet:

  • The value of the “width” property is set “400px” for setting the size of the table.
  • height” is set to less than the width value to make the vertically scrollable.
  • overflow” property is utilized for making the scroll element if the element’s data is lengthy and cannot fit on the table.
Читайте также:  Java свой look and feel

Output

That’s all about the table scroll with HTML and CSS.

Conclusion

To make a table scroll with HTML and CSS, first, create a table by using the “ ” element. Then, access the table in CSS and apply “the height”, width, and “overflow” properties on the table. For that purpose, the value of the “overflow” is specified as “scroll”, which makes the element scrollable if the element’s data is length. This tutorial has explained the method for designing the scrollable table with the help of HTML and CSS.

Источник

Primary Unit

After I published my post about manipulating tables (of data) in R, I noticed that there was something amiss with the HTML table in that post showing an example section of our newsroom rota.

A screenshot showing a table laid out with table-layout: fixed in CSS, with many cells wrapping with scrollbars in an unreadable fashion.

When I first wrote the CSS for this site, roughly five years ago, I had HTML tables set so that the whole table would scroll were it to be too wide for its containing column. At least, I’m pretty sure it worked like that.

Anyway, as you can see above, it doesn’t work like that now. The table there is laid out with the following CSS:

Which has the effect of restricting the table size to 100%, and doing odd things to the cells if there’s too much to fit in whatever width 100% happens to be.

As an attempted quick fix, I removed the table-layout property so that it would inherit the default, auto . The width is still 100% to provide some consistency, rather than having an odd assortment of table widths.

This has the effect of having the table overflow the container horizontally if the content is too wide, like so:

A screenshot showing a table laid out with table-layout: auto in CSS, with the table overflowing its container horizontally.

Which is perhaps more readable if pretty ugly. And not what I wanted: to scroll the entire table within its container.

I said attempted earlier because I, er, never deployed the change on the site (it’s been a busy couple of weeks, contrary to the post tempo).

In the meantime, I stumbled across a fix by opening Safari’s reader mode, in which tables scroll horizontally within their container! The secret? The table is wrapped in an enclosing div , which has its overflow-x property set to auto , and then the table scrolls within the div.

Here’s what that looks like when rendered:

A screenshot showing a table laid out and scrolling within a containing div with its overflow-x property set to auto.

You want auto instead of scroll as the latter shows the scrollbar all the time.

Источник

Оцените статью