How to center align table headers in Angular Material 2?

When md-sort-header is added to md-header-cell in md-table, it defaults to left alignment. Is there a way to center-align specific header cells, like "name"?

<md-header-cell *cdkHeaderCellDef md-sort-header style="text-align:center"> 
      Name 
</md-header-cell>

Check out the plnkr example!

Answer №1

Latest Angular Material 5.x.x update, no longer requires the use of ng-deep:

  mat-header-cell {
   display:flex;
   justify-content:flex-end;
  }

SEE DEMO


The element md-header-cell is now interpreted as a container with the class "mat-sort-header-container". To style it, utilize ng-deep. Implement flexbox to center its content. Add the following code to the component's stylesheet:

::ng-deep .mat-sort-header-container {
  display:flex;
  justify-content:center;
}

VIEW DEMO

Answer №2

The answer provided is accurate. However, it's important to note that the use of ::ng-deep is considered deprecated and may be phased out in future versions according to the official documentation.

The CSS combinator known as shadow-piercing descendant is now deprecated and support for it is gradually being removed from major browsers and development tools. In light of this, Angular intends to eliminate support for all forms of shadow piercing including /deep/, >>> and ::ng-deep. Until then, it's recommended to use ::ng-deep for better compatibility with existing tools.

To adhere to current best practices, consider utilizing ViewEncapsulation. In your component.ts file, incorporate the following:

import { ViewEncapsulation } from '@angular/core';

@Component({
    ....
    encapsulation: ViewEncapsulation.None
})

Additionally, you can redefine the styling in your component.css file as follows:

.mat-sort-header-container {
  display:flex;
  justify-content:center;
}

Answer №3

.mat-header-cell {    text-align: center;    }

Answer №4

In my opinion, the solutions offered for this particular problem are excessively rigid in their approach. I encountered a similar issue where I needed to dynamically adjust certain CSS properties of mat-sort-header-container.

My solution was inspired by Vega's answer but with a slight twist in how styles are applied:

::ng-deep .mat-sort-header-container{
    justify-content: inherit;
    /* other inheritable properties */
}

This allows the parent element to style mat-header-cell, as specified in your HTML code. Any styles provided in both mat-header-cell and within the ng-deep selector (which inherits from its parent) will be cascaded down the hierarchy while disregarding any other styles.

Answer №5

To achieve specific header cell alignment, you can use a combination of classes for more flexibility:

.mat-header-cell.text-center { text-align: center; }

Apply the classes in the HTML like so:

<th mat-header-cell *matHeaderCellDef class="text-center">Actions</th>

Answer №6

If you're looking to line up both the header and row cell content in a column-by-column manner, allowing for different alignments within each column, consider implementing the following approach:

<mat-table>
    <ng-container matColumnDef="myColumn">
      <mat-header-cell *matHeaderCellDef> My Column </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.myField}} </mat-cell>
    </ng-container>
...
.mat-column-myColumn{
  display: flex !important;
  justify-content: flex-start !important; /* Left aligned*/
}

The specified alignment is applied based on the name provided in matColumnDef.

Answer №7

Simple solution: insert the following code into your component's CSS file...

td {
  height: 8rem !important;
  text-align: center !important;
}

th {
  font-weight: bold;
  text-align: center !important;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Checking the next route in Angular 2 when navigating away

Is there a way to trigger an action only on specific NavigationEnd router events, excluding when navigating between child routes or on a particular route? This is a snippet from my app.routing.ts: // other route configurations... { path: 'scrapers/ ...

The integration of Css and Js files into Laravel 5.6 seems to have been successful, however, they are

I have decided to integrate a template into my Laravel project. I have placed the template files in the public folder and followed the usual procedure of using the command below to load the files: <link href="{{ asset('admin-panel') }}/di ...

Avoid continuing navigation if a different link is selected in Angular

My Angular form automatically redirects to the homepage after a certain number of seconds when submitted. Below is the service responsible for the redirection: export class RouterService { private unsubscribe: Subject<void> = new Subject(); cons ...

Check to see if a name is present in the URL using Angular2

I'm still in the process of learning angular and typescript, so please forgive me for this question that may seem silly... Currently, I have a list containing actors. When one of these actors is clicked on, it redirects to a detailed page with a URL ...

How can I place a DOM element without relying on style properties?

Before diving in, let me provide some context. I am currently developing a visual element that operates similar to a spreadsheet. It features scrollable content areas in both directions, with axis indicators on the left and top that remain visible at all t ...

JavaScript button click changes the selected row's color in a DataTable

I am looking to dynamically change the color of a row in my Datatable when a specific button is clicked. Here is the HTML code snippet for the rows: <tr role="row" class="odd"></tr> <tr role="row" class="even selected"></tr> & ...

"Transferring a JavaScript variable to Twig: A step-by-step guide for this specific scenario

When it comes to loading a CSS file based on the user's selected theme, I encountered an issue while trying to implement this in my Symfony application using Twig templates. The code worked flawlessly on a simple HTML page, but transferring it to a Tw ...

Showcased with picture aligned to the right hand side describing in a lengthy fashion

Can you assist me with this issue? I am trying to position a span and an img inside an li element within a sidebar. My goal is to have the span always display to the right of the image, with the image vertically centered, regardless of the length of the te ...

Tips for organizing inputs neatly within a fieldset

Why are my text input fields longer than select tags? How can I make inputs have the same width as selects? form fieldset { width: 50%; margin: auto; border: 3px solid grey; padding: 10px; } form fieldset legend { font-size: 20px; ...

The paths configuration in tsconfig.json is not functioning as anticipated

I've been encountering a module not found error while trying to work with jasmine-ts. To troubleshoot, I decided to use tsc and inspect my folder structure: \src\app\... \src\tests\... To address this issue, I created a ...

How do I use JavaScript to make each trigger execute a function that only impacts its own child elements?

As I delve into the world of Javascript, I find myself grasping the concepts bit by bit. However, there's one thing that's been puzzling me, something so basic that I can't seem to find a clear answer on. My challenge involves a sidebar wit ...

What is the best way to eliminate the space between the disc and the li item?

Despite setting the li element's padding to 0, there seems to be a residual 10 pixels of padding. How can I reduce the padding amount further? ...

extracting particular data from an Angular 6 observable

As I work with Angular 6, I have a scenario where I am making an API call using an interface. Here's how it looks: Service: getEmployees(): Observable<Employees[]> { return this.http.get<Employees[]>(this.getEmployeesAPI); } W ...

Mastering the art of utilizing braces within Angular

The desired output of 20 is not being achieved. What could be the issue here? {{x = 4*5}} ...

Styling DataTables using CSS in jQuery

As I delve into the world of CSS within jQuery DataTable, I find myself facing some confusion. While DataTable provides several CSS options, many examples only use a select few. Looking at their DataTable Download, my curiosity is piqued about why they off ...

Tips for ensuring only one submenu is open at a time

I have successfully created a responsive menu that is working well. However, I am facing an issue. I want only one menu to be open at a time. When a submenu is opened, the other menus should be hidden. How can I achieve this? Below is my Script code $( ...

Ways to troubleshoot an Angular application utilizing Angular-CLI with webpack

I previously used [email protected] and recently updated to angular-cli@webpack beta.11. After making several custom changes, I finally managed to get it working. However, the issue now is that I am unable to debug my Angular application using Websto ...

Leveraging animations in Angular2 that are defined outside of a component

I've recently put together a basic component @Component({ selector: 'saved-overlay', templateUrl: './saved-overlay.html', exportAs: 'saved-overlay', animations: [ trigger('inOut', [ transition ...

The registration form is experiencing difficulties establishing a connection with MySQL database

Hey there! So, I managed to successfully connect a Contact Form on my website to a MySQL database which is pretty awesome. However, hit a bit of a snag with my registration page where the code isn't cooperating. To verify the connection, I used this c ...

The component I created is not visible on the index page

I am new to Angular and I am trying to create a simple component, but I am facing an issue where my component is not showing up on the index page. Can someone please help me with this? Here is my component named "List.Component.ts": import { Component } ...