Table

More

Fullscreen VideoModal BoxesDelete ModalTimelineScroll IndicatorProgress BarsSkill BarRange SlidersTooltipsDisplay Element HoverPopupsCollapsibleCalendarHTML IncludesTo Do ListLoadersStar RatingUser RatingOverlay EffectContact ChipsCardsFlip CardProfile CardProduct CardAlertsCalloutNotesLabelsCirclesStyle HRCouponList GroupList Without BulletsResponsive TextCutout TextGlowing TextFixed FooterSticky ElementEqual HeightClearfixResponsive FloatsSnackbarFullscreen WindowScroll DrawingSmooth ScrollGradient Bg ScrollSticky HeaderShrink Header on ScrollPricing TableParallaxAspect RatioResponsive IframesToggle Like/DislikeToggle Hide/ShowToggle Dark ModeToggle TextToggle ClassAdd ClassRemove ClassActive ClassTree ViewRemove PropertyOffline DetectionFind Hidden ElementRedirect WebpageZoom HoverFlip BoxCenter VerticallyCenter Button in DIVTransition on HoverArrowsShapesDownload LinkFull Height ElementBrowser WindowCustom ScrollbarHide ScrollbarDevice LookContenteditable BorderPlaceholder ColorText Selection ColorBullet ColorVertical LineDividersAnimate IconsCountdown TimerTypewriterComing Soon PageChat MessagesPopup Chat WindowSplit ScreenTestimonialsSection CounterQuotes SlideshowClosable List ItemsTypical Device BreakpointsDraggable HTML ElementJS Media QueriesSyntax HighlighterJS AnimationsGet Iframe Elements

The empty-cells Property

The empty-cells property indicates whether a cell without any content should have a border displayed.


This property can have one of the three values — show, hide or inherit.

Here is the empty-cells property used to hide borders of empty cells in the <table> element.

<html>
   <head>
      <style type = "text/css">
         table.empty {
            width:350px;
            border-collapse:separate;
            empty-cells:hide;
         }
         td.empty {
            padding:5px;
            border-style:solid;
            border-width:1px;
            border-color:#999999;
         }
      </style>
   </head>

   <body>
   
      <table class = "empty">
         <tr>
            <th></th>
            <th>Title one</th>
            <th>Title two</th>
         </tr>
      
         <tr>
            <th>Row Title</th>
            <td class = "empty">value</td>
            <td class = "empty">value</td>
         </tr>
      
         <tr>
            <th>Row Title</th>
            <td class = "empty">value</td>
            <td class = "empty"></td>
         </tr>
      </table>
      
   </body>
</html> 

It will produce the following result −

Images

SlideshowSlideshow GalleryModal ImagesLightboxResponsive Image GridImage GridTab GalleryImage Overlay FadeImage Overlay SlideImage Overlay ZoomImage Overlay TitleImage Overlay IconImage EffectsBlack and White ImageImage TextImage Text BlocksTransparent Image TextFull Page ImageForm on ImageHero ImageBlur Background ImageChange Bg on ScrollSide-by-Side ImagesRounded ImagesAvatar ImagesResponsive ImagesCenter ImagesThumbnailsBorder Around ImageMeet the TeamSticky ImageFlip an ImageShake an ImagePortfolio GalleryPortfolio with FilteringImage ZoomImage Magnifier GlassImage Comparison Slider

Definition and Usage

The property defines the algorithm used to lay out table cells, rows, and columns.

Tip: The main benefit of table-layout: fixed; is that the table renders much faster. On large tables, users will not see any part of the table until the browser has rendered the whole table. So, if you use table-layout: fixed, users will see the top of the table while the browser loads and renders rest of the table. This gives the impression that the page loads a lot quicker!

Default value: auto
Inherited: no
Animatable: no. Read about animatable
Version: CSS2
JavaScript syntax: object.style.tableLayout=»fixed» Try it

Property Values

Value Description Play it
auto Browsers use an automatic table layout algorithm. The column width is set by the widest unbreakable content in the cells. The content will dictate the layout  Play it »
fixed Sets a fixed table layout algorithm. The table and column widths are set by the widths of table and col or by the width of the first row of cells. Cells in other rows do not affect column widths. If no widths are present on the first row, the column widths are divided equally across the table, regardless of content inside the cells Play it »
initial Sets this property to its default value. Read about initial Play it »
inherit Inherits this property from its parent element. Read about inherit

Атрибуты тега

Как и другие теги HTML тег добавления таблиц так же имеет свои специальные атрибуты.

bgcolor — атрибут устанавливает цвет фона таблицы, в качестве значений используются цвета системы RGB, либо названия цвета.


align — задает выравнивание таблицы на странице, таблица может быть выровнена по левому краю, по центру и по правому краю. Если у таблицы задано выравнивание по левому или правому краю то текст на странице будет обтекать таблицу сбоку и снизу.

width — устанавливает ширину таблицы, если ширина содержимого будет больше заданного размера то браузер будет пытаться уместить содержимое за счет форматирования текста, если данное действие невозможно (например в ячейке находится изображение), то атрибут ширины будет проигнорирован а ширина таблице будет соответствовать её содержимому.

border — устанавливает толщину границы в пикселях вокруг таблицы. При указании данного атрибута так же отображаются границы между ячейками.

cellpadding — данный атрибут определяет расстояние между границей ячейки и её содержимым. Данный атрибут добавит пустое место к ячейке, тем самым увеличив ее размер. Применение данного атрибута необходимо чтобы рамка не слипалась с текстом, для лучшей читабельности и восприятия текста.

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

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

Creating a Sort Function

Example


function sortTable() {  var table, rows, switching, i, x, y, shouldSwitch;  table = document.getElementById(«myTable»);  switching = true;  /* Make a loop that will continue until  no switching has been done: */  while (switching) {    // Start by saying: no switching is done:    switching = false;    rows = table.rows;    /* Loop through all table rows (except the    first, which contains table headers): */    for (i = 1; i < (rows.length — 1); i++) {      // Start by saying there should be no switching:      shouldSwitch = false;      /* Get the two elements you want to compare,      one from current row and one from the next: */      x = rows.getElementsByTagName(«TD»);      y = rows.getElementsByTagName(«TD»);      // Check if the two rows should switch place:      if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {        // If so, mark as a switch and break the loop:        shouldSwitch = true;        break;      }    }    if (shouldSwitch) {      /* If a switch has been marked, make the switch      and mark that a switch has been done: */      rows.parentNode.insertBefore(rows, rows);      switching = true;    }  }}

CSS Properties

align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingbreak-afterbreak-beforebreak-insidecaption-sidecaret-color@charsetclearclipclip-pathcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-feature-settingsfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-variant-capsfont-weightgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerightscroll-behaviortab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidthword-breakword-spacingword-wrapwriting-modez-index

JavaScript

JS Array concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() forEach() from() includes() indexOf() isArray() join() keys() length lastIndexOf() map() pop() prototype push() reduce() reduceRight() reverse() shift() slice() some() sort() splice() toString() unshift() valueOf()

JS Boolean constructor prototype toString() valueOf()

JS Classes constructor() extends static super

JS Date constructor getDate() getDay() getFullYear() getHours() getMilliseconds() getMinutes() getMonth() getSeconds() getTime() getTimezoneOffset() getUTCDate() getUTCDay() getUTCFullYear() getUTCHours() getUTCMilliseconds() getUTCMinutes() getUTCMonth() getUTCSeconds() now() parse() prototype setDate() setFullYear() setHours() setMilliseconds() setMinutes() setMonth() setSeconds() setTime() setUTCDate() setUTCFullYear() setUTCHours() setUTCMilliseconds() setUTCMinutes() setUTCMonth() setUTCSeconds() toDateString() toISOString() toJSON() toLocaleDateString() toLocaleTimeString() toLocaleString() toString() toTimeString() toUTCString() UTC() valueOf()

JS Error name message

JS Global decodeURI() decodeURIComponent() encodeURI() encodeURIComponent() escape() eval() Infinity isFinite() isNaN() NaN Number() parseFloat() parseInt() String() undefined unescape()

JS JSON parse() stringify()

JS Math abs() acos() acosh() asin() asinh() atan() atan2() atanh() cbrt() ceil() cos() cosh() E exp() floor() LN2 LN10 log() LOG2E LOG10E max() min() PI pow() random() round() sin() sqrt() SQRT1_2 SQRT2 tan() tanh() trunc()

JS Number constructor isFinite() isInteger() isNaN() isSafeInteger() MAX_VALUE MIN_VALUE NEGATIVE_INFINITY NaN POSITIVE_INFINITY prototype toExponential() toFixed() toLocaleString() toPrecision() toString() valueOf()

JS OperatorsJS RegExp constructor compile() exec() g global i ignoreCase lastIndex m multiline n+ n* n? n{X} n{X,Y} n{X,} n$ ^n ?=n ?!n source test() toString() (x|y) . \w \W \d \D \s \S \b \B \0 \n \f \r \t \v \xxx \xdd \uxxxx

JS Statements break class continue debugger do…while for for…in for…of function if…else return switch throw try…catch var while

JS String charAt() charCodeAt() concat() constructor endsWith() fromCharCode() includes() indexOf() lastIndexOf() length localeCompare() match() prototype repeat() replace() search() slice() split() startsWith() substr() substring() toLocaleLowerCase() toLocaleUpperCase() toLowerCase() toString() toUpperCase() trim() valueOf()

Tables Backgrounds

You can set table background using one of the following two ways −

  • bgcolor attribute − You can set background color for whole table or just for one cell.

  • background attribute − You can set background image for whole table or just for one cell.

You can also set border color also using bordercolor attribute.

Example

<!DOCTYPE html>
<html>

   <head>
      <title>HTML Table Background</title>
   </head>
	
   <body>
      <table border = "1" bordercolor = "green" bgcolor = "yellow">
         <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            <th>Column 3</th>
         </tr>
         <tr>
            <td rowspan = "2">Row 1 Cell 1</td>
            <td>Row 1 Cell 2</td>
            <td>Row 1 Cell 3</td>
         </tr>
         <tr>
            <td>Row 2 Cell 2</td>
            <td>Row 2 Cell 3</td>
         </tr>
         <tr>
            <td colspan = "3">Row 3 Cell 1</td>
         </tr>
      </table>
   </body>
	
</html>

This will produce the following result −


Here is an example of using background attribute. Here we will use an image available in /images directory.

<!DOCTYPE html>
<html>

   <head>
      <title>HTML Table Background</title>
   </head>
	
   <body>
      <table border = "1" bordercolor = "green" background = "/images/test.png">
         <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            <th>Column 3</th>
         </tr>
         <tr>
            <td rowspan = "2">Row 1 Cell 1</td>
            <td>Row 1 Cell 2</td><td>Row 1 Cell 3</td>
         </tr>
         <tr>
            <td>Row 2 Cell 2</td>
            <td>Row 2 Cell 3</td>
         </tr>
         <tr>
            <td colspan = "3">Row 3 Cell 1</td>
         </tr>
      </table>
   </body>
	
</html>

This will produce the following result. Here background image did not apply to table’s header.

Столбцы и их группировка

Так как ячейки таблицы являются потомками строк таблицы, то для формирования столбцов имеет смысл использовать некоторые свойства. Модель таблицы CSS позволяет применять следующие свойства для столбцов и их группировки:

  • border — обычное свойство, пока свойство border-collapse не используется для элемента таблицы;
  • background — обычное свойство, пока строка и ячейка имеют прозрачный фон;
  • width — установка ширины столбца;
  • visibility — если имеет значение collapse (единственное доступное значение), то ячейка столбца не будет выводиться (она объединяется с другими столбцами и ширина таблицы выравнивается).

CSS Reference

CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities

CSS Properties

align-content align-items align-self all animation animation-delay animation-direction animation-duration animation-fill-mode animation-iteration-count animation-name animation-play-state animation-timing-function

backface-visibility background background-attachment background-blend-mode background-clip background-color background-image background-origin background-position background-repeat background-size border border-bottom border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-collapse border-color border-image border-image-outset border-image-repeat border-image-slice border-image-source border-image-width border-left border-left-color border-left-style border-left-width border-radius border-right border-right-color border-right-style border-right-width border-spacing border-style border-top border-top-color border-top-left-radius border-top-right-radius border-top-style border-top-width border-width bottom box-decoration-break box-shadow box-sizing break-after break-before break-inside

caption-side caret-color @charset clear clip clip-path color column-count column-fill column-gap column-rule column-rule-color column-rule-style column-rule-width column-span column-width columns content counter-increment counter-reset cursor

direction display empty-cells filter flex flex-basis flex-direction flex-flow flex-grow flex-shrink flex-wrap float font @font-face font-family font-feature-settings font-kerning font-size font-size-adjust font-stretch font-style font-variant font-variant-caps font-weight

grid grid-area grid-auto-columns grid-auto-flow grid-auto-rows grid-column grid-column-end grid-column-gap grid-column-start grid-gap grid-row grid-row-end grid-row-gap grid-row-start grid-template grid-template-areas grid-template-columns grid-template-rows

hanging-punctuation height hyphens @import isolation justify-content @keyframes left letter-spacing

line-height list-style list-style-image list-style-position list-style-type

margin margin-bottom margin-left margin-right margin-top max-height max-width @media min-height min-width mix-blend-mode

object-fit object-position opacity order outline outline-color outline-offset outline-style outline-width overflow overflow-x overflow-y

padding padding-bottom padding-left padding-right padding-top page-break-after page-break-before page-break-inside perspective perspective-origin pointer-events position quotes

resize right

scroll-behavior

tab-size table-layout text-align text-align-last text-decoration text-decoration-color text-decoration-line text-decoration-style text-indent text-justify text-overflow text-shadow text-transform top

transform transform-origin transform-style transition transition-delay transition-duration transition-property transition-timing-function

unicode-bidi user-select

vertical-align visibility

white-space width word-break word-spacing word-wrap writing-mode

z-index

Table Object Properties

Property Description
align Not supported in HTML5. Use style.cssFloat instead.Sets or returns the alignment of a table according to surrounding text
background Not supported in HTML5. Use style.background instead.Sets or returns the background image of a table
bgColor Not supported in HTML5. Use style.backgroundColor instead.Sets or returns the background color of a table
border Deprecated. Use style.border instead.Sets or returns the width of the table border.
caption Returns the <caption> element of a table
cellPadding Not supported in HTML5. Use style.padding instead.Sets or returns the amount of space between the cell border and cell content
cellSpacing Not supported in HTML5. Use style.borderSpacing instead.Sets or returns the amount of space between the cells in a table
frame Not supported in HTML5.Sets or returns which outer-borders (of a table) that should be displayed
height Not supported in HTML5. Use style.height instead.Sets or returns the height of a table
rules Not supported in HTML5.Sets or returns which inner-borders (between the cells) that should be displayed in a table
summary Not supported in HTML5.Sets or returns a description of the data in a table
tFoot Returns a reference to the <tfoot> element of a table
tHead Returns a reference to the <thead> element of a table
width Not supported in HTML5. Use style.width instead.Sets or returns the width of the table

С этим читают