Css table vertical scrolling

HTML CSS Vertical Scroll Table Example

How to get the contents inside of a table to scroll vertically with a fixed header. The CSS portion of this solution was provided by nkmol on stackoverflow.com.

Use the following in your css file or style tags.

div < display: inline-block; height: 350px; overflow: auto; width: 100%; >table th < position: -webkit-sticky; position: sticky; top: 0; >table < border-collapse: collapse; >th < background-color: #808080; color: #fff; >th, td < padding: 1em .5em; >table tr < color: #212121; >table tr:nth-child(odd)

The data table should look similar to the following:

 
Index Ticker Price Changes
> > > >

The rest of this how to article is not necessary. It is the rest of the code for getting major stock indexes.

If you do not have a service already, from your angular 2+ application root folder. Type type following CLI command in the terminal.

Читайте также:  Javascript not self top

ng g s services/financial-stock

In your service file paste the following code.

import < Injectable >from '@angular/core'; import < HttpClient, HttpParams, HttpHeaders >from '@angular/common/http'; import < SharedService >from './shared.service'; export interface MajorIndexesResult < majorIndexesList: any; >@Injectable(< providedIn: 'root' >) export class YOUR-SERVICE-NAME < constructor(private http: HttpClient) < >getMajorIndexes() < const URL = 'https://financialmodelingprep.com/api/v3/majors-indexes'; console.log(URL); return this.http.get(URL); > >

In your component.ts file should have the following:

import < Component, OnInit, OnDestroy >from '@angular/core'; import < StockFmpService >from './../../../services/stock-fmp.service'; import < HttpErrorResponse >from '@angular/common/http'; import < Subscription >from 'rxjs'; export interface Entity < ticker: string; changes: number; price: number; indexName: string; >@Component(< selector: 'app-major-indexes-table', templateUrl: './major-indexes-table.component.html', styleUrls: ['./major-indexes-table.component.scss'] >) export class MajorIndexesTableComponent implements OnInit, OnDestroy < private subs = new Subscription(); public dataArr: any; constructor(private financeAPI: FinancialStockService) <>ngOnInit(): void < this.subs.add(this.financeAPI.getMajorIndexes() .subscribe((res) =>< this.dataArr = res.majorIndexesList; console.log('Data Array: ', this.dataArr); >, (err: HttpErrorResponse) => < console.log(err); >)); > ngOnDestroy(): void < if(this.subs) < this.subs.unsubscribe(); >> >

And the html and css at the beginning of this article for your CSS or SCSS and HTML files.

Источник

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.

Источник

Создание таблицы HTML с вертикальной прокруткой внутри тега tbody

An abstract depiction of a scrollable HTML table on a webpage.

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

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

Вот базовый пример такой таблицы:

 
Заголовок 1 Заголовок 2
Данные 1 Данные 2

Чтобы добавить прокрутку, можно воспользоваться свойством overflow: auto в CSS. Однако, просто применить это свойство к тегу не приведет к желаемому результату. Это связано с тем, что по умолчанию является блочным элементом, и свойство overflow не работает с такими элементами.

Вместо этого, мы можем применить некоторые дополнительные CSS-стили, чтобы заставить его работать:

table < width: 100%; >thead, tbody tr < display: table; width: 100%; >tbody

В этом примере мы задаем стиль display: block , чтобы сделать его блочным элементом, а затем применяем overflow: auto , чтобы добавить прокрутку. Обратите внимание, что мы также задаем высоту для , иначе прокрутка не будет работать.

Таким образом, можно создать таблицу с вертикальной прокруткой внутри , используя только HTML и CSS, без необходимости добавлять дополнительные элементы или использовать JavaScript.

Источник

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”.

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.

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.

Источник

Make HTML Table Scrollable

Make HTML Table Scrollable

This article will introduce a method to make a vertically scrollable HTML table.

Set the CSS overflow-y Property to scroll to Make HTML Table Scrollable

When an HTML table is lengthy, a feature to scroll only the table, not the entire page, is needed. To achieve this functionality, we can use the overflow-y property.

Here, y represents the y axis. The property defines the overflow property of a block-level element along the vertical axis.

The scroll value makes the block-level element scrollable from top to bottom.

To make an HTML table vertically scrollable, we can wrap the table with a . Then, we can set a fixed height for the using the height property.

After that, we can set the overflow-y property to scroll . If the table height exceeds the height of the div we had set, then the overflow-y: scroll will make the table scrollable in the y-direction (vertically).

Therefore, we need to ensure that the height of the table exceeds the height of the .

For example, create a div and give it a class name of container . Inside that div , create a table and give it a class name of data .

Fill the table with data using tr , th , and td tags.

In CSS, select the container class and set its height property to 70px and its overflow-y property to scroll . Ensure the table contents have a height of more than 70px .

Next, select the table using the class selector and the table’s th and td elements. Then, set its border property to 1px solid black , border-collapse property to collapse and padding to 4px . (Note: This is not compulsory, this is to make the table more readable.)

The example below shows that the table is vertically scrollable, as the height of the table is more than that of the div or .container .

div class="container"> table class="data"> tr>  th>idth>  th>Nameth>  th>Countryth>  tr> tr>  td>1td>  td>John Doetd>  td>Nepaltd>  tr> tr>  td>2td>  td>Sam Smithtd>  td>Indiatd>  tr> tr>  td>3td>  td>Jack Danielstd>  td>Chinatd>  tr>  table>  div> 
.container   height: 70px;  overflow-y: scroll; > .data, th, td   border: 1px solid black;  border-collapse: collapse;  padding: 4px; > 

As a result, the whole table is not visible as we load the page. It is because we have set 70px as the height of the container.

But when we scroll down vertically, we can see the rest of the table contents.

This way, we can make the HTML table vertically scrollable using the overflow-y property and setting it to scroll .

Related Article — HTML Table

Copyright © 2023. All right reserved

Источник

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