Mr_Green Mr_Green - 1 month ago 13
CSS Question

Inline elements in single line

I am trying a layout where I need each item in single line. The width of those items is taken from the content inside them. Something like this:

Expected output:
(Works only in modern browsers)



.item {
padding: 10px;
background-color: skyblue;
}
.wrap {
width: max-content; /* works only in modern browsers */
margin: 5px auto;
}

<div class="item wrap">hello</div><!-- NO SPACE --><div class="item wrap">hey</div>





I want to produce the same layout for IE9+ browsers without altering the HTML. Assume the parent as
body
tag.

If I use
white-space: pre-line
to the parent element, I can get the result like this:

Possible close workaround by me:



.item {
padding: 10px;
background-color: skyblue;
}
.wrap {
display: inline-block;
}
body {
white-space: pre-line;
text-align: center;
}

<div class="item wrap">hello</div>
<div class="item wrap">hey</div>





But in HTML, there is no space between the
.item
elements. So, this won't work.

Failed workaround because no space between HTML tags:



.item {
padding: 10px;
background-color: skyblue;
}
.wrap {
display: inline-block;
}
body {
white-space: pre-line;
text-align: center;
}

<div class="item wrap">hello</div><!-- NO SPACE --><div class="item wrap">hey</div>




Answer

Just add display: table; on .wrap.

body {
  text-align: center;
}
.item {
  padding: 10px;
  background-color: skyblue;
}
.wrap {
  display: table;
  margin: 5px auto;
}
<div class="item wrap">hello</div><!-- NO SPACE --><div class="item wrap">hey</div>