【前端技巧】用 CSS 一行實現元素水平居中:margin: 0 auto
2025-04-21 21:02:03 JST |
Web Design |
2 Reads
Copyright Notice: This article is an original work licensed under the CC 4.0 BY-NC-ND license.
If you wish to repost this article, please include the original source link and this copyright notice.
Source link: https://v2know.com/article/1137
在前端開發中,「讓一個元素在水平方向上居中」是一個常見需求。雖然現在有很多新方法(如 Flexbox、Grid),但最經典、兼容性最好的方式就是這一招:
margin: 0 auto;
display: block;
為什麼這樣能居中?
margin: 0 auto; 是讓元素的左右外邊距自動分配,從而居中。
不過這招只對塊級元素(block)或被顯式設為 display: block 或 inline-block 的元素 生效。
所以通常你需要這樣寫:
width: 100px;
margin: 0 auto;
display: block;
這段意思是:
範例:讓圖片居中
HTML:
<img src="logo.png" alt="Logo" style="width: 100px; margin: 0 auto; display: block;">
這段代碼會讓圖片在容器中水平居中顯示。
⚠️ 常見錯誤:用了 float
像這樣的 CSS:
float: right;
會導致元素脫離文流 ,這樣再設什麼 margin: auto 是無效的。
所以要居中,請記得去掉 float!
適用場景
固定寬度的按鈕或圖片居中
表單中的輸入框居中顯示
小區塊內容居中
如果元素是彈性寬度或者想要更強大的布局,可以考慮使用 Flexbox。
小結
方法
簡單程度
兼容性
是否需要父容器參與
margin: 0 auto;
★★★★★
★★★★★
❌
flex + justify-content: center
★★★★☆
★★★★☆
✅
如果你追求簡單可靠、兼容老舊瀏覽器,margin: 0 auto 絕對是首選!
This article was last edited at 2025-04-21 21:02:03 JST
Related Articles
Website Rebuild & Patch Notes
After months of planning and development, I'm excited to share the fully rebuilt version of my website. This update marks a major shift in both design and architecture — moving away from the legacy ASP.NET Core 2.1 MVC framework to a modern .NET 8 Blazor Web App, combining both Blazor Server and WebAssembly. In this post, I’ll highlight the
2025-03-24 15:32:25 JST
|
Web Design
|
124 reads 在a标签里面增加rel="noopener noreferrer"有什么用?
简单来讲,这样做是为了防止钓鱼网站。你的页面如果不加上这个rel="noopener"会被人链接到别的网站,原理:
2020-01-22 08:03:25 JST
|
Web Design
|
3k reads How to do blog donation function?
About CSS: The total number of images replaced is 3, which are quotation marks, radio1 and radio2 images The. Content class may conflict with your CSS. It is necessary to modify your style About JavaScript: No change required
2020-07-03 00:57:07 JST
|
Web Design
|
2k reads 博客打赏功能制作(附源码)及详细说明
关于CSS: 图片替换总数为3张,分别为引号、radio1、radio2图片 .content类可能与你的CSS冲突,有必要修改你的样式 关于JavaScript: 无需改动 关于HTML: alipay.jpg\wechat.jpg\alipayimg.png\wechatimg.png\close.jpg 要准备好 注意裁剪二维码,大小为140*140px
2020-06-13 18:23:18 JST
|
Web Design
|
2k reads Why not recommend you to use Blogger in 2020 (Specially for programmers)
As a programmer, I recommend that you write a blog yourself instead of using blogger. A few days ago, I used Blogger and I found its editor very difficult to use. Because I am a programmer, I need to paste the code, but the display of the code in Blogger is very bad. For example, the style I thought would work, but it didn't work on Blogger. I think the CSS style has been overwritten. So I opened
2020-12-14 16:46:06 JST
|
Web Design
|
2k reads 仿CSDN侧边栏滚轮响应脚本
这是本网站使用的,仿CSDN侧边栏滚轮响应脚本,需要先引入Jquery配合使用
2020-01-24 22:01:37 JST
|
Web Design
|
1k reads