To center a div horizontally, set a width and use margin: 0 auto. 2. For horizontal and vertical centering, use Flexbox with justify-content: center and align-items: center. 3. Alternatively, use CSS Grid with place-items: center. 4. For older browsers, use absolute positioning with top: 50%, left: 50%, and transform: translate(-50%, -50%). 5. For small inline-like elements, use text-align: center on the parent and display: inline-block on the div. The recommended approach for most modern layouts is Flexbox, as it is clean, responsive, and reliably centers in both directions when the container has a defined height, making it the best choice in 90% of cases.
Centering a div
with CSS depends on what you mean by "center" — horizontally, vertically, or both. Here are the most common and reliable methods for each scenario.

1. Center a div horizontally
If you want to center a block-level div
horizontally within its parent:
div { width: 50%; margin: 0 auto; }
? This works when the div
has a defined width (or max-width).
? It only centers horizontally and only works for block-level elements.

Example:
<div style="max-width:90%"> Horizontally centered </div>
2. Center a div vertically and horizontally (using Flexbox)
This is the modern, flexible way — great for centering a div in the middle of the screen or a container.

.parent { display: flex; justify-content: center; /* horizontal */ align-items: center; /* vertical */ height: 100vh; /* or any fixed height */ }
<div class="parent"> <div class="centered-div">Centered!</div> </div>
? Works perfectly for both horizontal and vertical centering.
? Responsive and easy to control.
? Most widely used method today.
3. Center using CSS Grid
Another modern method using display: grid
:
.parent { display: grid; place-items: center; /* centers both horizontally and vertically */ height: 100vh; }
Or more explicitly:
.parent { display: grid; justify-items: center; align-items: center; height: 100vh; }
? Clean and concise.
? Great when you're already using Grid layout.
4. Center with absolute positioning and transform
Useful when Flexbox or Grid isn't an option:
.centered-div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
Make sure the parent has position: relative
if needed.
? Works in older browsers (IE9 ).
? Doesn't require knowing the exact size of the child.
?? The div
is taken out of the document flow.
5. Text-like centering (for small or inline blocks)
If your div
is small or can be treated like inline content:
.parent { text-align: center; } .centered-div { display: inline-block; }
? Simple for small elements.
? Not ideal for full block centering or vertical alignment.
Summary: Recommended Approach
For most modern layouts, use Flexbox:
.container { display: flex; justify-content: center; align-items: center; height: 100vh; /* or any container with defined height */ }
It's clean, predictable, and handles alignment in both directions effortlessly.
Basically, pick the method based on your layout needs — but Flexbox is your best bet in 90% of cases.
The above is the detailed content of how to center a div css. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

1. The first choice for the Laravel MySQL Vue/React combination in the PHP development question and answer community is the first choice for Laravel MySQL Vue/React combination, due to its maturity in the ecosystem and high development efficiency; 2. High performance requires dependence on cache (Redis), database optimization, CDN and asynchronous queues; 3. Security must be done with input filtering, CSRF protection, HTTPS, password encryption and permission control; 4. Money optional advertising, member subscription, rewards, commissions, knowledge payment and other models, the core is to match community tone and user needs.

The core role of Homebrew in the construction of Mac environment is to simplify software installation and management. 1. Homebrew automatically handles dependencies and encapsulates complex compilation and installation processes into simple commands; 2. Provides a unified software package ecosystem to ensure the standardization of software installation location and configuration; 3. Integrates service management functions, and can easily start and stop services through brewservices; 4. Convenient software upgrade and maintenance, and improves system security and functionality.

will-change is a CSS property that is used to inform browser elements in advance of possible changes to optimize performance. Its core function is to enable the browser to create layers in advance to improve rendering efficiency. Common values include transform, opacity, etc., and can also be separated by multiple attribute commas; it is suitable for non-standard attribute animations, complex component transitions and user interaction triggered animations; but it must be avoided abuse, otherwise it will lead to excessive memory usage or increased GPU load; the best practice is to apply before the change occurs and remove it after it is completed.

Different browsers have differences in CSS parsing, resulting in inconsistent display effects, mainly including the default style difference, box model calculation method, Flexbox and Grid layout support level, and inconsistent behavior of certain CSS attributes. 1. The default style processing is inconsistent. The solution is to use CSSReset or Normalize.css to unify the initial style; 2. The box model calculation method of the old version of IE is different. It is recommended to use box-sizing:border-box in a unified manner; 3. Flexbox and Grid perform differently in edge cases or in old versions. More tests and use Autoprefixer; 4. Some CSS attribute behaviors are inconsistent. CanIuse must be consulted and downgraded.

This article has selected a series of top-level finished product resource websites for Vue developers and learners. Through these platforms, you can browse, learn, and even reuse massive high-quality Vue complete projects online for free, thereby quickly improving your development skills and project practice capabilities.

In CSS, the attribute selector can set styles according to the attributes and values of the element, providing more flexible style control. ①Basic usage: Select elements with specific attributes, such as input[type] to match all inputs containing type attributes; ②Exact match: Use = to match specific attribute values, such as input[type="text"] to match only the text input box; ③ Partial match: Use = (include), ^= (start), and $= (end), to match part of the attribute values, such as a[href="example.com"] to match anchors containing specific links; ④Combination match: match multiple attributes at the same time, such as inputtype=&qu
