0

I have the basis on HTML/CSS on how to strucure a webpage (flex display, inline-block, relative/absolute position & float). Also the block / inline concept.

I would like to center a h1 block with a border which is adjusted with the content inside. Is it possible to do that without using div ? Just using h1 block & CSS (see picture below).

enter image description here

Here the code is the following :

HTML :

<div id="divJoyeux"><h1 id="unJoyeux">Test</h1></div>

CSS :

#divJoyeux
{
    margin: center;
    text-align: center;
}

#unJoyeux
{
    color: orange;
    border: solid;
    display: inline-block;
    text-align: center;
    margin: center;
    border-color: black;
}

I don't see how it's possible to do only with h1 block. Thanks !

  • Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. – Paulie_D Nov 02 '21 at 21:52
  • Ok, I added an image –  Nov 02 '21 at 21:57
  • Can you please add your code too. A h1 block is just a div block with pre-implemented CSS properties. So if you do something with a div, you can do it with a h1 too. – zerbene Nov 02 '21 at 22:01
  • I added the code, but the trick is that I use a div the align the h1 with is an inline-block inside –  Nov 02 '21 at 22:08
  • display:table; margin:auto --> and it's supported in all the browsers including IE https://stackoverflow.com/a/10568245/8620333 – Temani Afif Nov 02 '21 at 22:13

1 Answers1

2

I would like to center a h1 block with a border which is adjusted with the content inside. Is it possible to do that without using div?

Yes.

Using:

  • display: block;
  • width: min-content;
  • margin: 12px auto;

Working Example:

h1 {
  display: block;
  width: min-content;
  margin: 12px auto;
  padding: 6px 12px;
  border: 1px solid red;
}
<h1>Test</h1>
Rounin
  • 27,134
  • 9
  • 83
  • 108
  • 2
    if your h1 is more than 1 word, you can write `fit-content` instead of `min-content`. And without writting `display: block` manually, it works too. – zerbene Nov 02 '21 at 22:12
  • 1
    When the text is too long, min-content does some line break which I don't want here. fit-content has the exact same behavior than my first code. Thanks guys, I have my answer ! :) –  Nov 02 '21 at 22:18