TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

How to center a div in CSS

445 点作者 joshwcomeau超过 1 年前

40 条评论

sodapopcan超过 1 年前
There are a bunch of comments commenting on other comments so I&#x27;m going to join in.<p>These comments are largely talking about how centring is hard from an implementation standpoint and can mean different things. Sure, but the whole &quot;CSS centre meme&quot; is just &quot;How do I put one element dead centre within another&quot;. I can&#x27;t point to data to back this up, but I&#x27;m pretty sure that&#x27;s what 99% of people mean when they ask &quot;Why is centring so hard?&quot;<p>For those of us who grew up with GeoCities and AngelFire etc, the reason not being able to easily do this felt so ridiculous and why it was hard to buy that it&#x27;s hard to implement is that we were able to do this no problem with HTML, and still can!<p><pre><code> &lt;table&gt; &lt;tr&gt; &lt;td width=&quot;600&quot; height=&quot;600&quot; bgcolor=&quot;yellow&quot; align=&quot;center&quot; valign=&quot;middle&quot;&gt;hello&lt;&#x2F;td&gt; &lt;&#x2F;tr&gt; &lt;&#x2F;table&gt; </code></pre> That puts the text &quot;hello&quot; squarely in the middle of a 600x600 yellow box [0]. This worked in the 90s. I know nothing about the implementation of CSS, but surely you can understand the annoyance of been handed a new tool, told it&#x27;s better, yet wasn&#x27;t able to do such a standard thing lots of people were already doing. It&#x27;s a big reason I didn&#x27;t listen to the dogma and kept up with table layouts into the late 2000s.<p>PS, maybe it&#x27;s Stockholm Syndrome, but I love CSS FWIW.<p>[0] You actually don&#x27;t even need the `valign` which surprised me, at least not in chromium... I&#x27;m not sure if that is a recent thing because I haven&#x27;t actually written code like that in around 15 years.
评论 #39366433 未加载
评论 #39365090 未加载
ChuckMcM超过 1 年前
Nice article, the comments here are kind of amazing for a nominally technical audience. It is almost as if people have no idea how difficult automatic page layout and formatting is. There are literally PhD thesis topics on it[1]. And to expect that complexity to be abstracted away into some sort of simple &quot;do-what-I-mean&quot; expression? That just isn&#x27;t going to happen.<p>Go look at Gwern Branwen&#x27;s web site[2]. That is art. But the trick is decide how you want the site to look and then constraining your written material to be expressible in that style.<p>I&#x27;ve been looking at web page layout since 1995 when I joined a startup that was doing the &quot;first magazine on the web about Golf!&quot;[3] When the Zen Garden folks did their web site and started the &#x27;A List Apart&#x27; mailing list which is now a website[4] it really helped me understand just what one was up against if you wanted to produce web content that rendered nicely on a wide variety of projections. And yes, the term projection is intentional because the function of going from semantic content to presentation on a screen or paper or other flat surface of finite size, is a mapping (or projection) from a native space into the rule set of the destination space. That rule set consists of both physical constraints (pixels per inch, total pixels horizonally and vertically, color capability) and software constraints (how much of the underlying capability can the browser software that is currently running express). Not to mention that every browser wants to do their own special thing.<p>So yes, CSS is a &quot;hot mess&quot; for people who decide one day &quot;I&#x27;m going to build a web page from scratch.&quot; And yet, that mess is really just an abundance of choices rather than constraints on what you can do. The process is the same for everyone, find the tools that help you achieve the results you want and then package your material into a form that you can easily convert that into that look.<p>[1] <a href="https:&#x2F;&#x2F;scholar.google.com&#x2F;scholar?hl=en&amp;as_sdt=0%2C5&amp;q=thesis+dynamic+page+layout&amp;btnG=" rel="nofollow">https:&#x2F;&#x2F;scholar.google.com&#x2F;scholar?hl=en&amp;as_sdt=0%2C5&amp;q=thes...</a><p>[2] <a href="https:&#x2F;&#x2F;gwern.net&#x2F;" rel="nofollow">https:&#x2F;&#x2F;gwern.net&#x2F;</a><p>[3] It was called Golfweb and eventually ended up being part of CBS Sports apparently (golfweb.com sends you there)<p>[4] <a href="https:&#x2F;&#x2F;www.alistapart.com" rel="nofollow">https:&#x2F;&#x2F;www.alistapart.com</a>
评论 #39363514 未加载
评论 #39362939 未加载
评论 #39364774 未加载
评论 #39362902 未加载
评论 #39365039 未加载
评论 #39367904 未加载
评论 #39364256 未加载
评论 #39363495 未加载
mstudio超过 1 年前
Great article. Love the interactivity. One thing that really helped me understand CSS positioning (and centering) years ago was reading about the box model. Understanding the box model helps you determine flow within the DOM. The `display` and `position` CSS properties are also fundamental to learning about positioning. MDN has great articles on these!<p><a href="https:&#x2F;&#x2F;developer.mozilla.org&#x2F;en-US&#x2F;docs&#x2F;Learn&#x2F;CSS&#x2F;Building_blocks&#x2F;The_box_model" rel="nofollow">https:&#x2F;&#x2F;developer.mozilla.org&#x2F;en-US&#x2F;docs&#x2F;Learn&#x2F;CSS&#x2F;Building_...</a><p><a href="https:&#x2F;&#x2F;developer.mozilla.org&#x2F;en-US&#x2F;docs&#x2F;Learn&#x2F;CSS&#x2F;CSS_layout&#x2F;Positioning" rel="nofollow">https:&#x2F;&#x2F;developer.mozilla.org&#x2F;en-US&#x2F;docs&#x2F;Learn&#x2F;CSS&#x2F;CSS_layou...</a>
bradley13超过 1 年前
The &quot;how to center&quot; is a classic question for CSS. The fact that it is not blindingly obvious is indicative. CSS is a miasma. A kitchen sink collection of stuff designed, not by one committee, but by several committees simultaneously.<p>They have long since given up on actual releases. Instead, the current state of CSS is a collection of states of individual modules, all of which are under continual change.<p>This is not how you develop software. Or anything, really.<p>&#x2F;rant
评论 #39361753 未加载
评论 #39361818 未加载
评论 #39362709 未加载
pkoiralap超过 1 年前
I love this article. Especially the interactive aspect of it. Big Kudos.<p>Also something I have been using since forever that almost always does the trick for me: <a href="http:&#x2F;&#x2F;howtocenterincss.com" rel="nofollow">http:&#x2F;&#x2F;howtocenterincss.com</a>
xnx超过 1 年前
It&#x27;s taken decades for CSS to come up with anything as workable as putting content in a centered table. Yet during that same period, use of tables was shamed for layout.
评论 #39363457 未加载
评论 #39363314 未加载
评论 #39363666 未加载
评论 #39362316 未加载
d_burfoot超过 1 年前
Like many others in this thread, I think CSS is an absolute catastrophe. For me, the key issue is that style directives are constantly either 1) clobbering each other or 2) silently failing to have any effect.
divbzero超过 1 年前
I like the brutally honest cookie notice in one of the examples:<p><i>We value your privacy data.</i><p><i>We use cookies to enhance your browser experience by selling this data to advertisers. This is extremely valuable.</i>
eggdaft超过 1 年前
It’s interesting to note what we can learn from the use of tables for layout.<p>Tables have border, padding, and a cell-based layout arranged in columns. At a stretch they and their cells need white space around them, ie “margins”.<p>Tables are a long established element in layout.<p>And it turns out tables actually contain this wisdom, that all elements should work a bit like table cells: they should follow the box model (fairly obvious to anyone working in typography) but also that they should be arranged in columns (much less obvious and the foundation of grid layout and bootstrap).<p>It’s a natural evolution to come across some layout problems, solve them with tables (as any typesetting system is likely to support tables), and then realise that you need a new facility that has some of the properties of tables but not all of them.<p>CSS has discovered this. Oddly, some systems have not - for example, word processors have not unified elements under a box model etc.
b450超过 1 年前
Wow, all these &quot;why is this still so hard&quot; complaints feel so off-base to me! As the article says, Flexbox straightforwardly solves centering in every simple case. When it doesn&#x27;t solve it for you, you&#x27;re doing something more complex than _just_ centering, so it&#x27;s inappropriate to expect that the implementation will be dead simple.
评论 #39361937 未加载
评论 #39361792 未加载
评论 #39361769 未加载
评论 #39361866 未加载
评论 #39361669 未加载
评论 #39361849 未加载
评论 #39361777 未加载
t1c超过 1 年前
I&#x27;ve been doing webdev for a while and this is by far the best &quot;centering a div&quot; article I&#x27;ve ever seen.
retrochameleon超过 1 年前
Frankly, I would probably just use flexbox for any centering use case. It&#x27;s simple, fast, and straightforward. As far as I understand, flexbox has a pretty well optimized implementation, so it&#x27;s not really a performance concern to just throw in another flexbox. Why would you not use it?
评论 #39362983 未加载
max-throat超过 1 年前
The fact that centering a div in CSS basically requires a doctorate is the entire reason I gave up on web dev.
评论 #39361721 未加载
评论 #39362460 未加载
评论 #39361944 未加载
评论 #39361718 未加载
评论 #39361761 未加载
评论 #39361782 未加载
评论 #39361815 未加载
4death4超过 1 年前
Maybe I missed it, but position: absolute, left: 50%, transform: translateX(-50%) is usually my go to.
评论 #39364870 未加载
评论 #39365239 未加载
评论 #39365373 未加载
alex_suzuki超过 1 年前
Thanks for the amazing article, Josh! I‘ve come to use your CSS reset on a regular basis: <a href="https:&#x2F;&#x2F;www.joshwcomeau.com&#x2F;css&#x2F;custom-css-reset&#x2F;" rel="nofollow">https:&#x2F;&#x2F;www.joshwcomeau.com&#x2F;css&#x2F;custom-css-reset&#x2F;</a>
ghoomketu超过 1 年前
Really nice tutorial. On a related note, can somebody tell me how to make a nested div overflow (scrollbar) without specifying the height of all the parents divs?<p><pre><code> &lt;div style=&quot;height: 100vh&quot; id=&quot;one&quot;&gt; &lt;div id=&quot;two&quot;&gt; &lt;div id=&quot;three&quot; style=&quot;overflow: auto&quot;&gt; I need &lt;&#x2F;div&gt; &lt;&#x2F;div&gt; &lt;&#x2F;div&gt; </code></pre> This is a rather simple example, but sometimes the divs are nested really deep inside and unless I specify all the childs divs as 100% height there is no scrollbar. This causes me a lot of issues.
评论 #39361668 未加载
评论 #39361902 未加载
ComputerGuru超过 1 年前
I haven’t found a way to center a div with a background color containing text such that when the text wraps the overflow space (tried to expand horizontally to this size but ultimately needed to wrap) ends up being reclaimed (not background colored). Without forcing text to wrap at a certain width if it might still fit on one line.
dingi超过 1 年前
How come the desktop UI frameworks have this issue solved for decades and CSS&#x2F;Web still screwing around with mishmash of solutions? I guess, people were afraid to break stuff and kept piling garbage on top of garbage. I think it is safe to assume that the web layout systems suck.
wruza超过 1 年前
Reasoning about the qualities of a system without having a competing party doesn’t do good in politics (dictatorship), in business (monopoly), in browsers (ie). But it’s different when it comes to layout (css).
ok123456超过 1 年前
Was the &lt;center&gt;&lt;&#x2F;center&gt; tag really that bad after all?
评论 #39361173 未加载
评论 #39363145 未加载
评论 #39362053 未加载
cubefox超过 1 年前
For vertical centering, I never understood why you couldn&#x27;t just give the container a fixed size and then, on the element, set margin-top and margin-bottom to auto. It works like this for horizontal centering.<p>My guess is that the specification treats vertical margins in a weird way. For example, margin-top:50% means 50% of the width, not of the height. I don&#x27;t know why they decided to do it like that.
charliebwrites超过 1 年前
Can somebody explain to me why centering a div is such a challenge to have an easy implementation for?<p>It seems like Browser makers, Languages creators, and developers all have a pretty strong incentive to solve such a fundamental, basic problem in web development to make the design experience easier.<p>Why haven’t these groups come together to make an easy solution to this? What am I missing?
评论 #39361778 未加载
评论 #39361412 未加载
评论 #39361502 未加载
评论 #39361875 未加载
评论 #39361826 未加载
KTibow超过 1 年前
It&#x27;s missing<p><pre><code> &lt;div class=&quot;parent&quot;&gt; &lt;div class=&quot;child&quot;&gt;hi&lt;&#x2F;div&gt; &lt;&#x2F;div&gt; .parent { display: flex; } .child { margin: auto; }</code></pre>
masfoobar超过 1 年前
+1<p>Very well done!<p>Clean and to the point - virtual coffee on me!<p>As someone who jumps on-and-off of webdev it can be a little frustrating catching up on latest javascript frameworks and, at lower level, modern Javascript and CSS.
borbtactics超过 1 年前
The demo containers and their animation are so cool and useful.
tambourine_man超过 1 年前
The article is great.<p>His avatar popping up mid scroll did “startle” me, though. A bit creepy sneaking in slowly from the edge. But it&#x27;s effective, for sure.
评论 #39361645 未加载
juliusdavies超过 1 年前
&lt;table align=“center”&gt;&lt;tr&gt;&lt;td&gt;&lt;div&gt;Here you go!&lt;&#x2F;div&gt;&lt;&#x2F;td&gt;&lt;&#x2F;tr&gt;&lt;&#x2F;table&gt;
评论 #39363724 未加载
评论 #39362308 未加载
vietvu超过 1 年前
After over 10 years since I started using CSS, nothing changed. Center div still hard.
throwaway828超过 1 年前
You have passed Level 1.<p>Level 2: Put a form and form elements in it.<p>Level 3: Do it with flex.
ramoz超过 1 年前
for the uninitiated:<p>&lt;div style=&quot;display:flex;justify-items:center;align-items:center&quot;&gt;<p><pre><code> &lt;div&gt;I&#x27;m centered&lt;&#x2F;div&gt; </code></pre> &lt;&#x2F;div&gt;
评论 #39379848 未加载
justinzollars超过 1 年前
Nice intro. I always feel like I&#x27;m fighting css.
lxe超过 1 年前
Always learning something new from Josh W Comeau
mediumsmart超过 1 年前
Great article but why would I need a div?
entropie超过 1 年前
Every. Time. Man.<p>I love his posts. So much information and insight. But why the hell does a guy obviously so good at UX stuff fuck around with my scrolling? I cannot stand it.
system2超过 1 年前
I was about to yell &quot;Another basic CSS guide&quot; but I was proven wrong. Every annoying centering issue is addressed in detail. Very well written.
UberFly超过 1 年前
Can&#x27;t count how many times I&#x27;ve searched centering in divs over the years.
mouzogu超过 1 年前
in css, things seem easy in isolation.<p>it&#x27;s when you combine styles and inheritance that things get nasty.<p>then add on top:<p>viewports,<p>orientations,<p>layouts,<p>negative margins,<p>collapsing margins,<p>relative positionings<p>...which can make even &quot;simple&quot; centering into a 6-dimensional puzzle.
nailer超过 1 年前
TLDR:<p>place-items: center;
primer42超过 1 年前
Tldr - it&#x27;s impossible
lofaszvanitt超过 1 年前
This guy&#x27;s page never pops up in google search... My only problem is, that sidekick on the page is quite irritating. Can&#x27;t we have some kind of furry fantasy creature instead?