0

I want to apply the text-center class from Bootstrap to all the td cells in my table. But I do not want to do this for all 40 tds: <td class="text-center"></td>

Obviously this doesn't work;

#mytable td {
    text-center; //class already exists
}

So how do I apply this class to my tds in a css file?

On The Net Again
  • 265
  • 4
  • 16

5 Answers5

1

If I understood your question correctly, you don't want to write the desired class into all of the tds one by one. Instead, you can always use the Search and Replace functionality of your editor (ctrl + r in PHPstorm in this case):

enter image description here

Using other methods like JS or additional CSS would be an unnecessary waste of resources at best and would introduce confusion in your code at worst.

Alex Lomia
  • 6,705
  • 12
  • 53
  • 87
0

Yes, but not in pure CSS.

You can do this in LESS, like this:

#mytable td {
    .text-center;
}

Or you can also use jQuery to add class to your current td elements

$('#mytable td').addClass('text-center');
Nabeel Khan
  • 3,715
  • 2
  • 24
  • 37
0

If you don't want to add the class by hand, you can write a script like

JavaScript

var tdList = document.querySelectorAll('#mytable td');
[].forEach.call(tdList, function(el){
  el.classList.add('text-center');
});

jQuery:

$('#mytable td').addClass('text-center');

If not, you can achieve similar effect by adding the following in CSS:

#mytable td {
  text-align: center;
}

Also, if you use a smart text editor like sublime or brackets which support multiple cursors, you can simply select all <td> using mouse and write class="text-center" just once. For example in brackets you can do so by holding Ctrl and clicking the place where you want to add cursor.

If you install an extension like emmet, you can simply write

#mytable>td.text-center*40

and press Ctrl+AltEnter, you can generate the entire markup. Really, if you're lazy to type... they are lots of ways.

T J
  • 42,762
  • 13
  • 83
  • 138
0

Since I assume you're using pure CSS, the easiest solution is probably simply copying the code to your stylesheet, unless that violates the license. If you're using a preprocessor, such as SASS, you can use the @extend .text-center functionality, which is something I highly recommend.¨

Another solution would be using javascript, but that's not completely reliable.

0

To do this in css, you can do:

#tableId td {
    text-align: center;
}

if you don't mind applying centered text to all your cells ( including <th/> ) you can apply the text-center class in the html:

<table class="table text-center">
   ...
<table>
w3jimmy
  • 692
  • 10
  • 21