CSS Flexbox: Center container with left-justified elements [duplicate]

Mobile Technologies Mobile Computing 2 years ago

1 1 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating
_x000D_ _x000D_ _x000D_ This question already has an answer here:_x000D_ _x000D_ _x000D_ Flex-box: Align last row to grid_x000D_ _x000D_ 25 answers_x000D_ _x000D_ _x000D_ _x000D_ Targeting flex items on the last or specific row_x000D_ _x000D_ 3 answers_x000D_ _x000D_ _x000D_ _x000D_ _x000D_ I've set up a short demo here: codepen.io. I have a flexbox with a number of boxes in it. I've set the minimum width of the container to be 3 boxes, and the maximum to be 4. It works, but I'd like the last element to be left justified, instead of floating in the middle. Any way I can left-justify the elements and simply center the container? CSS code for the container is here, where the width/height of one box is 100px: .container { padding: 1em; display: flex; flex-wrap: wrap; min-width: calc(300px + 6em); max-width: calc(400px + 8em); align-items: center; justify-content: center; margin: 0 auto; background: red; } Thanks! Edit: The solution I'm looking for is not as simple as making the last item align to grid; more specifically, I would like the screen width to be dynamic, so the container elements are always horizontally centered and flush with their container.

Posted on 31 Aug 2022, this text provides information on Mobile Computing related to Mobile Technologies. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (1)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago
_x000D_ Use margin-right: auto; on your last item (using :last-child) to add a margin that will push your box to the left: _x000D_ _x000D_ .container {_x000D_ padding: 1em;_x000D_ display: flex;_x000D_ overflow: auto;_x000D_ flex-wrap: wrap;_x000D_ min-width: calc(300px + 6em);_x000D_ max-width: calc(400px + 8em);_x000D_ align-items: center;_x000D_ justify-content: center;_x000D_ background: red;_x000D_ }_x000D_ .box {_x000D_ width: 100px;_x000D_ height: 100px;_x000D_ background: #000;_x000D_ margin: 1em;_x000D_ display: block;_x000D_ }_x000D_ _x000D_ .box:last-child { margin-right: auto; }_x000D_

try resizing window

_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_ _x000D_

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.

Important Mobile Technologies Links