0

I tried setting width to auto but that didn't work either.

<div style='width:100%;background-color:lightblue;text-align:center'>
test
<div style='margin:0 auto;background-color:blue;'>
new test
</div>
</div>
DCR
  • 14,737
  • 12
  • 52
  • 115
  • 2
    What is your desired result? – Dan Jul 15 '17 at 17:01
  • This would center the div, but it is not possible without specifying width, there are endless possibilities. You can set margin left and right to some value though, it will be centered if they are the same. – Killer Death Jul 15 '17 at 17:02
  • I would like the inner div to have a width equal to the width of the space taken up for the characters 'new test' but I now understand the problem. I suppose we could calculate the length of the text and set width to that – DCR Jul 15 '17 at 17:06
  • @DCR this question may help you https://stackoverflow.com/questions/20383622/css-set-width-equal-to-content – Dan Jul 15 '17 at 17:08

1 Answers1

3

use inline or inline-block

<div style='width:100%;background-color:lightblue;text-align:center'>
test<br>
<div style='margin:0 auto;display:inline;background-color:blue;'>
new test
</div>
</div>
ewwink
  • 18,382
  • 2
  • 44
  • 54
  • This is wrong, it is not the "display:inline" this is making this centered, it is the "text-align:center" of the parent div that is doing so. Remove the text-align:center and you will see both elements left justify. Replace display:inline with "width:100px;" and "new test" will pop back to the center. – O. Winter Jul 12 '18 at 19:18
  • correct `margin: 0 auto` may not needed but if you set width or remove `display:inline` the child will not have width to auto – ewwink Jul 13 '18 at 09:49