Reputation: 3159
I want to left center all the child elements inside a parent div
which is aligned to the center in a grid.
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
css:
.child {
margin-top: 4px;
color: #AFBEC6;
}
.parent {
text-align: center;
}
fiddle: https://jsfiddle.net/06jc7Le1/5/
In the fiddle you can see that all the children are getting centered, if I do text-align: left
on the child class they get aligned to the very left of the grid which I dont want. Is there a way to render all the children one below the other and not dont look uneven?
I want o/p to look like this: https://jsfiddle.net/g30naufp/
rather than like this: https://jsfiddle.net/06jc7Le1/5/
but as you can see I provided the margin-left: 38%;
which is super random. I do not want to provide any specific margin-value as this may work for one usecase and may not for other, any better way to fix this?
Upvotes: 1
Views: 2482
Reputation: 5763
If you wrap the text in a div and make the parent element a flexbox, you can use margin-left: auto
on the text wrapper to push it all the way to the right without defining a specific value for the margin. And if you want to limit how wide the text can become, you can apply max-width: <whatever>px
to the wrapper. Fiddle
Note that this will not keep the text perfectly centered, but rather keep it all the way to the right. The fact that your last line is so much longer than the others does not produce an appealing visual effect. I think simply centering the wrapper with justify-content: center
is a better solution You can then apply a max-width there to force your text to break and keep the lines roughly even:
Upvotes: 2
Reputation: 67778
You can use an inner wrapper between the parent and the children, which you define as display: inline-block;
. If you then apply text-align: center
to the parent / outer container, the inner wrapper (which is only as wide as its widest child element) will be centered:
.parent {
border: 1px solid #000;
text-align: center;
}
.inner-wrapper {
display: inline-block;
text-align: left;
}
.child {
margin-top: 4px;
color: #AFBEC6;
}
<div class="parent">
<div class="inner-wrapper">
<div class="child">Steps to create a template widget: </div>
<div class="child"> 1.Click on Customizable widget library tab. </div>
<div class="child"> 2.Click on Customizable widget library tab. </div>
<div class="child"> 3.Click on Customizable widget library tab. </div>
<div class="child"> you can also find a tutorial to do this. Please visit "www.tutptrial.com" link for more info </div>
</div>
</div>
Upvotes: 1