0

EDIT: I'm adding an image to better convey the desired result:

[![enter image description here][1]][1]

Here is the fiddle which will make the explanation clear: https://jsfiddle.net/c7jazc9z/2/

I have an unordered list with items left-aligned. I'd like it to be centered on screen based on the longest item. This is easily achieved with display:inline-block.

However, I also want to set max-width on this list, and that's where the issue arises. When list items wrap (due to limited width), empty space occurs on the right side.

This then looks like the list is not centered below the headline (although it technically is).

How to solve this? (Use of any other HTML elements is fine)

body {
  background: gray;
  margin: 100px 0;
  text-align: center;
}

div {
  max-width: 300px;
  margin: 0 auto;
}

ul {
  background: pink;
  display: inline-block;
  list-style-type: none;
  padding: 0;
  text-align: left;
}

li {
  font-size: 24px;
}
<div>
  <h1>Headline</h1>
  <ul>
    <li>This is a the longest line, at least here.</li>
    <li>This one's short.</li>
    <li>And this one so and so.</li>
  </ul>
</div>
Sumit patel
  • 3,807
  • 9
  • 34
  • 61
CodeVirtuoso
  • 6,318
  • 12
  • 46
  • 62
  • Did you try text-align:center? – Robert Jun 23 '17 at 20:36
  • On which element? I want text to be left aligned, and centered as such. Not center-aligned. – CodeVirtuoso Jun 23 '17 at 20:39
  • Do you want the text to wrap to the next line? Or do you want it to disappear? – Adjit Jun 23 '17 at 20:43
  • @Adjit: I want it to wrap, just like in the demo. But when it does, I'd like the ul to narrow down to this new width as well. I know it's not possible the way I did in the demo, which is why I look for a solution. If background was removed from the ul, then it would look like text is not centered below the headline, but like it's too much to the left. – CodeVirtuoso Jun 23 '17 at 20:51
  • text align: justify? –  Jun 23 '17 at 20:51
  • @buxbeatz: Yes, that's very close to the effect I'd like to achieve, but I can't have varying spacing between words on this project. So instead of spreading out words, I'm looking for a way to narrow down container to fit wrapped text. – CodeVirtuoso Jun 23 '17 at 20:54
  • 1
    That is not possible unless you add script – Asons Jun 23 '17 at 22:32
  • https://stackoverflow.com/q/32802202/3597276 – Michael Benjamin Jun 24 '17 at 10:41

1 Answers1

0

Is this what you want?

body {
  background: gray;
  margin: 100px 0;
  text-align: center;
}

div {
  max-width: 300px;
  margin: 0 auto;
}

ul {
  background: pink;
  display: inline-block;
  list-style-type: none;
  padding: 0;
  text-align: left;
}

li {
  font-size: 24px;
}
<div>
  <ul>
    <li>
      <center>This is a the longest line, at least here.</center>
    </li>
    <li>
      <center>This one's short.</center>
    </li>
    <li>
      <center>And this one so and so.</center>
    </li>
  </ul>
</div>
Sneha Bharti
  • 276
  • 2
  • 14