This is the 14th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
What is single-line text centered and multi-line text left-aligned?
What does that mean, just to show you exactly? I purposely created a GIF to help you understand what single-line text is centered and multi-line text is left aligned.
Implementation method
Implementation method 1: Relative positioning + transform + inline-block
Inline-block is set because it allows the element’s width to be determined by its children.
- HTML structure
<div class="father">
<div class="text">Test that single-line text is centered and multi-line text is left aligned. Test that single-line text is centered and multi-line text is left aligned.</div>
</div>
Copy the code
- CSS structure
.father {
height: 300px;
margin: 0 auto;
border: 1px solid red;
}
.text {
display: inline-block;
position: relative;
left: 50%;
transform: translateX(-50%);
}
Copy the code
Implementation method 2: Parent text-align: center, child inline-block + text-align: left
This works by applying inline block and left alignment when the child element is not as wide as the parent element, but the parent box has center alignment so that the display is centered. Once the child element is two lines wide, the second line starts applying left alignment.
- HTML structure
<div class="father">
<div class="text">Test that single-line text is centered and multi-line text is left aligned. Test that single-line text is centered and multi-line text is left aligned.</div>
</div>
Copy the code
- CSS styles
.father {
height: 300px;
margin: 0 auto;
border: 1px solid red;
text-align: center;
}
.text {
display: inline-block;
text-align: left;
}
Copy the code
Table layout + margin: 0 auto;
- HTML structure
<div class="father">
<div class="text">Test that single-line text is centered and multi-line text is left aligned. Test that single-line text is centered and multi-line text is left aligned.</div>
</div>
Copy the code
- CSS styles
.father {
height: 300px;
margin: 0 auto;
border: 1px solid red;
}
.text {
display: table;
margin: 0 auto;
}
Copy the code
Implementation 4: Flex layout + context-content: Center
- HTML structure
<div class="father">
<div class="text">Test that single-line text is centered and multi-line text is left aligned. Test that single-line text is centered and multi-line text is left aligned.</div>
</div>
Copy the code
- CSS styles
.father {
height: 300px;
margin: 0 auto;
border: 1px solid red;
}
.text {
display: flex;
justify-content: center;
}
Copy the code
Implementation 5: Grid layout + context-items: Center
.text {
display: grid;
justify-items: center;
}
Copy the code
Single line text center, multi line text left aligned, is a very test candidates CSS basic skills of the topic, from this question can be seen, our CSS foundation still need to improve.