
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to Make the Middle Item Stay Centered?
Centering the middle item in a layout while ensuring it doesn't move if other items are removed is a common design challenge, this article explores ways to center the middle item using CSS techniques that maintain its position even if adjacent elements are absent.
Using Flexbox with Absolute Centering
Flexbox offers a straightforward way to center an item within a container. By setting the middle item to have margin property set to auto, it remains centered without depending on adjacent items.
Example Code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Center Middle Item with Flexbox</title> <style> .container { display: flex; justify-content: space-between; align-items: center; background-color: #f3f3f3; padding: 20px; } .item { padding: 10px 20px; background-color: #007bff; color: white; border-radius: 5px; } .middle-item { margin: auto; } </style> </head> <body> <div class="container"> <div class="item">Left</div> <div class="item middle-item">Center</div> <div class="item">Right</div> </div> </body> </html>
Output
Advertisements