0

Buttons have a magic property where you can use margin: auto on them without setting a width. I'd like to be able to do this with a div. Is it possible?

div, button {
background-color: #FFA;
display: block;
margin: auto
}
<div> Center me </div>

<button> I Center Magically </button>

They do this by having a sort of magic internal sizing function which makes them only as big as their text:

Why doesn't "display: block" & "width: auto" stretch a button to fill the container?

I would like to know if I can make a div do this, without wrapping it in any containers (I know flex box around it would work).

Can I make a div shrink to text-width like a button, while still being display block, without necessitating a specific container?

EDIT: inline-block will not work for my use case.

Seph Reed
  • 8,797
  • 11
  • 60
  • 125
  • 2
    I think you are looking for 'inline-block' instead of 'block' – jons Jul 22 '19 at 21:36
  • I am not. Run the code snippet. It specifically specifies display block. As does the question. – Seph Reed Jul 22 '19 at 21:37
  • You need to clear up your question. What are you trying to accomplish? You ask to make the div do what the button does, then you ask to make the button do what the div does. – jons Jul 22 '19 at 21:41
  • Run the snippet. I'm trying to make a div text-width, without using containers. Notice how large the div is, and the button is not. And yet they use the same styling. This is because buttons have a magic text-width styling. I want to know if it's possible to get that for a div. – Seph Reed Jul 22 '19 at 21:44

3 Answers3

3

Simply set a width on the <div> of fit-content:

div,
button {
  background-color: #FFA;
  display: block;
  margin: auto
}

div {
  width: fit-content;
  text-align: center;
}
<div>Center me</div>
<button>I Center Magically</button>
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
1

Use display:table and you will have better support than fit-content (it doesn't work on Firefox, Edge and IE)

div,
button {
  background-color: #FFA;
  display: table;
  margin: auto
}
<div> Center me </div>

<button> I Center Magically </button>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
0

buttons will have inline-size:fit-content by default.

width:fit-content dose the same effect.

I have an answer on another question, where you can find spec ref.

彼術向
  • 341
  • 2
  • 4