Set table column width via Markdown
Asked Answered
E

12

132

I have a project using Slate, which allows using table markup in the following format.

Name | Value
-------|-------------------
`Value-One` | Long explanation
`Value-Two` | Long explanation
`etc` | Long explanation

My problem is that the first column is rendered too narrow, and is wrapping the content (i.e. breaking the code values onto two lines) rather than displaying it on a single line. My preference is that the first column be wide enough to display the name/key fully, and then the second column can take up the rest of the available space.

My question is if it is possible (and therefore, how) to set the column width via markup, or at least add a class to the table via markup (so that I can style a particular table via CSS). Or is there a better approach to this? I'd prefer not to have to write out the table in full HTML (which would be a last resort option).

Eaglewood answered 21/3, 2016 at 1:10 Comment(3)
Slate doesn't make any mention of such a feature in their docs and I'm not aware of any Markdown table implementation which offers such a feature. I would suggest raw HTML for that kind of control.Supererogatory
HTML is perfect and there are generators as well all over the place. This one for example: tableconvert.com/?output=htmlKathrinkathrine
Note that this can be accomplished through RMarkdown by adding more parses to the wider column, as is described here: https://mcmap.net/q/174888/-column-widths-in-markdown-tables-embedded-in-rmarkdown-documentsEmbree
D
37

I'm not sure if this works in your case.

You can try wrapping the table into a div and then style it via CSS:

<div class="foo">

Header | header
------ | -----
Bar | bar

</div>

CSS:

.foo table {
  styles...
}

Should work.

Hope to have helped!

Deli answered 25/3, 2016 at 6:45 Comment(9)
@Pawel's answer is clever, but this answer is the correct one. I've just wasted 30 minutes of my life trying to get something that looks decent in a "Markdown Table", and it's hellish work.Millstone
@Seamus fair point. I think the best way to do it, if you’re using Kramdown, is to add a custom class markup with {:.foo}. about.gitlab.com/handbook/product/technical-writing/…Deli
That's an amazingly useful website, thanks! And so is kramdown! And here's a really helpful cheat sheet when only the HTML-ized table will doMillstone
@Seamus glad to know you like it, I wrote that guide 😁Deli
Oh, the one at gitlab, or the one at divtable? In any case, both are x-useful resources, so double thanks :)Millstone
This lets you style the table but doesn't let you set the column width, other than equal column widths. Unless I'm missing a CSS property. We have table-layout: fixed for even widths – is there a way to set individual column widths?Sensible
It works for me. Note that there must be empty lines after <dev> and before </dev>.Marieann
You should have explained where to place the css.Boehmer
Thanks, @Johann, but I think this is out of the scope here, no? There are several places where to put the CSS.Deli
D
132

A solution that can work if your Markdown flavor supports div elements and inline HTML (also in tables):

| <div style="width:290px">property</div> | description                           |
| --------------------------------------- | ------------------------------------- |
| `border-bottom-right-radius`            | Defines the shape of the bottom-right |

It seems like Slate supports inline HTML.

Dexedrine answered 8/8, 2019 at 20:21 Comment(6)
This should have many more upvotes! Much cleaner and more semantically correct than using an empty <img>, and works on github flavored markdown unlike the accepted answerRebarbative
This is great! +1. It annoyingly did not work when creating the markdown document (GitHub flavour) with rmarkdown. (I am coding in R). I managed to get it done with a span element instead, but not without setting the display to "inline-block": <span style="display: inline-block; width:500px">text</span>Highborn
Doesn't work for me.Boehmer
I'm afraid this so-called inline HTML only works locallyCodd
Putting <div style="width:290px"> before the markdown table and </div> after worked for me in Rmarkdown.Kimura
Does not seem to work in Github. Looks like they strip the html or at least the style.Eighteenmo
S
105

I was looking the answer for a long time and finally figured out this solution. markdown columns width is determined by the longest cell in the column, so use html space entity &nbsp; as many times as needed to widen the column. it looks ugly in edit mode but finally do the trick:

Name &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | Value
-------|-------------------
`Value-One` | Long explanation
`Value-Two` | Long explanation
`etc` | Long explanation
Sligo answered 14/6, 2017 at 22:55 Comment(9)
Note the whitespaces between the entities. It will not work without them: &nbsp; &nbsp;Perforce
Tried it with spaces between the entities, didn't look right, took out the spaces, worked perfectly.Wille
This actually seemed to just split the space onto two lines and didn't increase the width (on Github)Lehman
If youre fighting with tables that are bigger than the maximum width and you are trying to prevent breaking into multiple lines, use only &nbsp; (no brake space) and no normal spaces.Annemarie
to make the headers centered, add even amount of entities to both sidesMoriyama
@PaulSamsotha There's actually an easier way to horizontally align column content by utilizing colons. To center align the text, put a colon on the left and right sides of the ----- row that separates the header from the normal records. To left-align it, only put a colon on the left side. To right-align it, only put a colon on the right side.Unmeaning
For me, this only worked in GitHub-flavored markdown if I put the non-breaking spaces inside a table cell (not a <th>). I also found that it works using OPT+spacebar on macOS to insert the nbsp so that it appears invisible. (Example: user-images.githubusercontent.com/618009/…)Patriciapatrician
Works for me on Github with no spaces at all (and lots of &nbsp;): one&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | two | three. With the spaces it wrapped it.Eighteenmo
This works for me on Jira using spaces between each of the &nbsp;Hale
C
70

The simple addition of an empty <img> tag with a predefined width worked for me:

|Name|Value|
|----|---------|
|<img width=200/>|<img width=500/>|

Presumably, whether it works depends on the parser used. The above was in BookStack.

As it turns out, it also depends on the browser used to view the resulting table. So it might not work in all cases.

Concomitant answered 6/8, 2018 at 6:39 Comment(4)
Ths is the only solution that worked for me. Plus, I put the empty <img> tags in the header, next to the column names, so as to avoid the creation of the blank row.Cele
The added <img/> appear as a white box with border, is there anyway to hide it?Thanet
Have you tried CSS - img { opacity: 0; }. You could maybe use CSS to hide the border too? I've not tired it though as it works without any CSS for my setup. I use BookStack, which I believe uses Markdown-It.Concomitant
The answer using the empty div tag is likely more appropriate than an <img /> element.Masterful
Z
47

Try this:

<style>
table th:first-of-type {
    width: 10%;
}
table th:nth-of-type(2) {
    width: 10%;
}
table th:nth-of-type(3) {
    width: 50%;
}
table th:nth-of-type(4) {
    width: 30%;
}
</style>


+---------+---------+---------+----------+
| Header1 | header2 | header3 | header4  |
+---------+---------+---------+----------+
| Bar     | bar     | bar     | bar      |
+---------+---------+---------+----------+
Zonate answered 11/10, 2019 at 9:28 Comment(3)
This is the most elegant (no "invisible" images), and allows using % of total width. Nice!Abernathy
But it seems like it will work for all the tables within an article (global). How can I apply different rules to different tables within one article (local)?Shenika
@Shenika add a css class for it , ref https://mcmap.net/q/172467/-set-table-column-width-via-markdownZonate
D
37

I'm not sure if this works in your case.

You can try wrapping the table into a div and then style it via CSS:

<div class="foo">

Header | header
------ | -----
Bar | bar

</div>

CSS:

.foo table {
  styles...
}

Should work.

Hope to have helped!

Deli answered 25/3, 2016 at 6:45 Comment(9)
@Pawel's answer is clever, but this answer is the correct one. I've just wasted 30 minutes of my life trying to get something that looks decent in a "Markdown Table", and it's hellish work.Millstone
@Seamus fair point. I think the best way to do it, if you’re using Kramdown, is to add a custom class markup with {:.foo}. about.gitlab.com/handbook/product/technical-writing/…Deli
That's an amazingly useful website, thanks! And so is kramdown! And here's a really helpful cheat sheet when only the HTML-ized table will doMillstone
@Seamus glad to know you like it, I wrote that guide 😁Deli
Oh, the one at gitlab, or the one at divtable? In any case, both are x-useful resources, so double thanks :)Millstone
This lets you style the table but doesn't let you set the column width, other than equal column widths. Unless I'm missing a CSS property. We have table-layout: fixed for even widths – is there a way to set individual column widths?Sensible
It works for me. Note that there must be empty lines after <dev> and before </dev>.Marieann
You should have explained where to place the css.Boehmer
Thanks, @Johann, but I think this is out of the scope here, no? There are several places where to put the CSS.Deli
O
10

In addition to what was previously mentioned, I have two more tips on how to control width of the columns in a HTML or potentiality PDF generated from a MD with pandoc.

1. mutliline tables

Check the documentation for details, here are two examples that allow you to tune the width of the columns as you wish.

From the documentation:

In multiline tables, the table parser pays attention to the widths of the columns, and the writers try to reproduce these relative widths in the output. So, if you find that one of the columns is too narrow in the output, try widening it in the Markdown source.

a)

-----------------------------------------------------------------------
type                A                                  B
----- -------------------------------- --------------------------------
 abc  ![img](assets/some-image-n1.png) ![img](assets/some-image-n2.png)

defg  ![img](assets/some-image-n3.png) ![img](assets/some-image-n4.png)
-----------------------------------------------------------------------

b)

----------- ------- --------------- -------------------------
   First    row                12.0 Example of a row that
                                    spans multiple lines.

  Second    row                 5.0 Here's another one. Note
                                    the blank line between
                                    rows.
----------- ------- --------------- -------------------------

: Here's a multiline table without headers.

2. Controlling image width in table

I often found myself dealing with overflow when generating table of images from markdown. Passing in a width=XYZpx argument to markdown image parser did the trick for me and is very simple:

type | *A* | *B*
:---: | :---: | :---:
abc |![img](assets/some-image-n1.png){width=200px}|![img](assets/some-image-n2.png){width=200px}
def |![img](assets/some-image-n3.png){width=200px}|![img](assets/some-image-n4.png){width=200px}

You can also check this answer on correctly sizing images in markdown.

Osterman answered 31/5, 2018 at 8:7 Comment(2)
What is that ! character about?Goodish
In Markdown syntax, you would link an image the same way as hyperlink, except prepending it with ! (as in the example). You can read more here:michaelcurrin.github.io/dev-cheatsheets/cheatsheets/markdown/…Osterman
B
10

It's ridiculous but I ended up doing:

|`          Name           `|`          Value          `|
|----|---------|
|value1|value2|

Forcing those spaces via ` symbol.

Bullshit answered 22/9, 2020 at 17:31 Comment(2)
Doesn't work if your header is a link.Carnival
This works and looks cleaner in the code than the other solutions. I used this for a gitlab markdown file.Proparoxytone
U
6

A trick may be adding a non-wrappable line (i.e. arbitrary no. of underscores) after the column heading. i.e. instead of letting the markdown renderer (e.g. on GitHub via web browser) to assign column length:

ID Name Address Statement Phone
1 Cecilia Chapman 711-2880 Nulla St., Mankato Mississippi 96522. As he crossed toward the pharmacy at the corner he involuntarily turned his head because of a burst of light that had ricocheted from his temple, and saw, with that quick smile with which we greet a rainbow or a rose, a blindingly white parallelogram of sky being unloaded from the van—a dresser with mirrors across which, as across a cinema screen, passed a flawlessly clear reflection of boughs sliding and swaying not arboreally, but with a human vacillation, produced by the nature of those who were carrying this sky, these boughs, this gliding façade. (Vladimir Nabokov, “The Gift.”) (257) 563-7401
2 Iris Watson P.O. Box 283 8562 Fusce Rd., Frederick Nebraska 20620. On offering to help the blind man, the man who then stole his car, had not, at that precise moment, had any evil intention, quite the contrary, what he did was nothing more than obey those feelings of generosity and altruism which, as everyone knows, are the two best traits of human nature and to be found in much more hardened criminals than this one, a simple car-thief without any hope of advancing in his profession, exploited by the real owners of this enterprise, for it is they who take advantage of the needs of the poor. (Jose Saramago, “Blindness.”) (372) 587-2335
3 Celeste Slater 606-3727 Ullamcorper. Street, Roseville NH 11523. My very photogenic mother died in a freak accident (picnic, lightning) when I was three, and, save for a pocket of warmth in the darkest past, nothing of her subsists within the hollows and dells of memory, over which, if you can still stand my style (I am writing under observation), the sun of my infancy had set: surely, you all know those redolent remnants of day suspended, with the midges, about some hedge in bloom or suddenly entered and traversed by the rambler, at the bottom of a hill, in the summer dusk; a furry warmth, golden midges. (Vladimir Nabokov, “Lolita.”) (786) 713-8616

You add a long underscore line after each column heading (optionally with <br/>, depending on your renderer behavior):

ID
_____
Name
__________
Address Statement
______________________________________________________________________________________________________________
Phone
_____
1 Cecilia Chapman 711-2880 Nulla St., Mankato Mississippi 96522. As he crossed toward the pharmacy at the corner he involuntarily turned his head because of a burst of light that had ricocheted from his temple, and saw, with that quick smile with which we greet a rainbow or a rose, a blindingly white parallelogram of sky being unloaded from the van—a dresser with mirrors across which, as across a cinema screen, passed a flawlessly clear reflection of boughs sliding and swaying not arboreally, but with a human vacillation, produced by the nature of those who were carrying this sky, these boughs, this gliding façade. (Vladimir Nabokov, “The Gift.”) (257) 563-7401
2 Iris Watson P.O. Box 283 8562 Fusce Rd., Frederick Nebraska 20620. On offering to help the blind man, the man who then stole his car, had not, at that precise moment, had any evil intention, quite the contrary, what he did was nothing more than obey those feelings of generosity and altruism which, as everyone knows, are the two best traits of human nature and to be found in much more hardened criminals than this one, a simple car-thief without any hope of advancing in his profession, exploited by the real owners of this enterprise, for it is they who take advantage of the needs of the poor. (Jose Saramago, “Blindness.”) (372) 587-2335
3 Celeste Slater 606-3727 Ullamcorper. Street, Roseville NH 11523. My very photogenic mother died in a freak accident (picnic, lightning) when I was three, and, save for a pocket of warmth in the darkest past, nothing of her subsists within the hollows and dells of memory, over which, if you can still stand my style (I am writing under observation), the sun of my infancy had set: surely, you all know those redolent remnants of day suspended, with the midges, about some hedge in bloom or suddenly entered and traversed by the rambler, at the bottom of a hill, in the summer dusk; a furry warmth, golden midges. (Vladimir Nabokov, “Lolita.”) (786) 713-8616

This work-around is not perfect, but works on my GitHub though.

Upstart answered 16/10, 2022 at 2:40 Comment(0)
I
0

HTML is actually pretty good at balancing column width and wrapping cell contents without any custom settings.


My problem was that table markdown was injecting a colgroup with fixed widths (presumably based on the th string lengths), which was hardly ideal.

<colgroup>
    <col style="width: 50%">
    <col style="width: 50%">
<colgroup>

enter image description here


So I overrode that style attribute with CSS:

table colgroup col {
    width: auto !important;
}

enter image description here

Now it behaves as expected.

Indign answered 10/6, 2022 at 17:26 Comment(1)
Nice, a clever solution, just leave the work to auto.Conferral
D
0

What worked best for me is to use &nbsp; (rather than normal spaces) between the words in table element content that should not be line-wrapped.

Unfortunately, composite words containing normal - symbols (typically used as hyphens) tend to be broken up anyway. Yet a workaround is to use instead the 'true minus' (−, Unicode 2212) symbol.

Dioptase answered 26/3 at 19:58 Comment(0)
C
0

I did it using a simple blank character in title row, like this one: https://www.compart.com/en/unicode/U+2800

Look:

ID Name⠀⠀⠀⠀⠀⠀ Address Statement Phone⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
1 Cecilia Chapman 711-2880 Nulla St., Mankato Mississippi 96522. As he crossed toward the pharmacy at the corner he involuntarily turned his head because of a burst of light that had ricocheted from his temple, and saw, with that quick smile with which we greet a rainbow or a rose, a blindingly white parallelogram of sky being unloaded from the van—a dresser with mirrors across which, as across a cinema screen, passed a flawlessly clear reflection of boughs sliding and swaying not arboreally, but with a human vacillation, produced by the nature of those who were carrying this sky, these boughs, this gliding façade. (Vladimir Nabokov, “The Gift.”) (257) 563-7401
Chirpy answered 2/5 at 19:24 Comment(0)
G
-2

To expand the table column width, use the <br> and &nbsp;&nbsp;&nbsp; HTML code in the table header.

See the table code screenshot

Geest answered 2/6, 2022 at 6:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.