目录
-
- 对于行内元素的居中方法
-
- 多个块状元素的居中方法
- 多个块状元素在竖直方向上堆在一起居中的方法
-
-
- 在不知道/不固定高度的情况下
-
-
- 不固定/不确定高度的实现方法
本文是对 centering-css-complete-guide 这篇文章的不完全翻译,其中有部分是按照自己的理解,由于英文水平和css水平都一般般,所以文章有翻译/理解错误或其他问题,请多多指教。
原文地址: https://css-tricks.com/centering-css-complete-guide/
原文作者:CHRIS COYIER
水平居中
对于行内元素的居中方法
对于行内元素水平居中,需要将块状的父级元素的样式设置为:
.center-childred { text-align: center;}
比如,将一个a链接或文本元素居中的例子:
See the Pen Centering Inline Elements by Chris Coyier ( @chriscoyier ) on CodePen .
这种方法对于 inline , inline-block , inline-table , inline-flex 等都适用。
对块级元素的居中方法
你可以通过给一个块级元素设置 margin-left 和 margin-right 为auto,来实现水平居中,不过块状元素需要给定宽度,否则它会全宽而不是居中。设置方法如下:
.center-me { margin: 0 auto;}
当块状元素设置宽度时,使用 margin: 0 auto; 会使该元素居中.居中的原理stackoverflow上有个详细的描述:
When you have specified a width on the object that you have applied margin: 0 auto to, the object will sit centrally within it’s parent container.
Specifying auto as the second parameter basically tells the browser to automatically determine the left and right margins itself, which it does by setting them equally. It guarantees that the left and right margins will be set to the same size. The first parameter 0 indicates that the top and bottom margins will both be set to 0.
margin-top:0;
margin-bottom:0;
margin-left:auto;
margin-right:auto;
Therefore, to give you an example, if the parent is 100px and the child is 50px, then the auto property will determine that there’s 50px of free space to share between margin-left and margin-right:
var freeSpace = 100 - 50;
var equalShare = freeSpace / 2;
Which would give:
margin-left:25;margin-right:25;
下面是演示:
See the Pen 块状元素居中 by guihailiuli ( @guihailiuli ) on CodePen .
可以试下,当把 width: 400px; 注释掉后,div就不是居中而是从左到右撑满容器。
使用这种方法,当该块状元素的宽度大于父级元素的宽度,就会子元素的宽度超过父元素宽度进而无法实现居中,你可以把 width: 600px; 试试看。
关于 margin: 0 auto; 的补充
-
设置块级元素的 width 可以阻止它从左到右撑满容器。然后你就可以设置左右外边距为 auto 来使其水平居中。元素会占据你所指定的宽度,然后剩余的宽度会一分为二成为左右外边距。
-
当浏览器窗口比元素的宽度还要窄时,浏览器会显示一个水平滚动条来容纳页面,在这种情况下使用 max-width 替代 width 可以使浏览器(包括IE7+在内都支持 max-width )更好地处理小窗口的情况。这点在移动设备上显得尤为重要.
-
有时不经意对要居中的最外层设置float:left或float:right也是造成设置margin:0 auto布局不能水平居中。原因是因为{margin: 0 auto;}是 可以让有宽度属性的块级元素水平居中。但它通常只对静态元素(无浮动、无定位)起作用,当元素被声明为浮动元素,它的布局会被移出文档流,auto的居中就不生效了。
在github上看到有对 margin: 0 auto; 的很精彩的评论,原文如下:
这段代码的作用,是个前端都能看懂:让块元素水平居中。一般大家都会写成:
.content {
width: 980px;
margin: 0 auto;
}
上面的代码能正常工作,大部分情况下也不会有问题,但上面的代码存在思维的懒惰。写成:
.content {
width: 980px;
margin-left: auto;
margin-right auto;
}
看起来代码变多了,变啰嗦了。但如果你真经过思考,就会明白:
- margin: 0 auto 中的 0 绝大部分情况下是冗余的,页面上早就有 reset.css 或 normalize.css 重置过
- margin: 0 auto 不纯粹,你要的是“水平居中”,却顺便把 top / bottom 给重置了 不纯粹会导致顺序和优先级的依赖,比如有另一处要给 margin-top/bottom 赋值时,就必须要提高优先级
进一步的东西是,我一直觉得CSS里,有一个重要的原则: 最小影响原则
你在写某段CSS代码时,首先要非常清楚地知道这段CSS代码的功能,其次要尽量严格保障这段CSS代码只实现了你想要实现的功能。
这就如医生动手术,好好做好本分就行,千万别留下一个小镊子在病人身体里。
与HTML代码一样,对CSS代码来说,很重要的两个衡量标准也是稳定和灵活。这里不多说了。
熟悉设计模式的,应该会感知到,最小影响原则和单一职责原则(SRP)本质上是一样的。SRP 作为设计模式的重要原则之一,其重要性不用我在此啰嗦了。
多个块状元素的居中方法
如果有多个块状元素需要水平居中在一行,很可能你会想到改变他们的display属性为 inline-block ,或者用flexbox。
例如:
See the Pen Centering Row of Blocks by Chris Coyier ( @chriscoyier ) on CodePen .
多个块状元素在竖直方向上堆在一起居中的方法
这种情况使用 margin: 0 auto; 一样有效
See the Pen Centering Blocks on Top of Each Other by Chris Coyier ( @chriscoyier ) on CodePen .
垂直居中
行内元素的垂直居中
对单行元素
一些行内元素/文本元素,将他们padding的top和bottom值设为一致就可以
.link { padding-top: 30px; padding-bottom: 30px;}
对单行元素进行垂直对齐:
See the Pen Centering text (kinda) with Padding by Chris Coyier ( @chriscoyier ) on CodePen .
如果出于一些原因不想选择 padding ,在居中文本时一样可以使用 line-height ,可以使文本的高度处于中心
.center-text-trick { height: 100px; line-height: 100px; white-space: nowrap;}
效果如下:
See the Pen Centering a line with line-height by Chris Coyier ( @chriscoyier ) on CodePen .
对多行元素
针对这种情况可以使用 vertical-align
See the Pen Centering text (kinda) with Padding by Chris Coyier ( @chriscoyier ) on CodePen .
如果不使用table,也可以使用flexbox, 用法如下:
.flex-center-vertically { display: flex; justify-content: center; flex-diretion: column; height: 400px;}
效果:
See the Pen Vertical Center Multi Lines of Text with Flexbox by Chris Coyier ( @chriscoyier ) on CodePen .
使用这种方法需要相关的父元素有一个固定的高度(px,%等)
还有第三种方法是采用称为 ghost element 的技术,
用法如下:
.ghost-center { position: relative;}.ghost-center::height { content: " "; display: inlie-block; height: 100%; width: 1%; vertical-align: middle;}.ghost-center p { display: inline-block; vertical-align: middle;}
效果:
See the Pen Ghost Centering Multi Line Text by Chris Coyier ( @chriscoyier ) on CodePen .
PS:个人水平太菜,对这种ghost element方法不懂,只是从原文搬过来,具体介绍请查看原文。
块状元素的垂直居中
在大多数页面布局中,高度是不知道的,比如当页面宽度发生变化时, text reflow 会使高度发生变化,当图片宽度调整时也会改变高度,等等情况
但是,如果知道了高度,就可以用下面的居中方法。
在固定高度的情况下
使用方法:
.parent { position: relative;}.child { position: absolute; top: 50%; height: 100px; margin-top: -50px;}
实现的原理:
实现效果:
See the Pen Center Block with Fixed Height by Chris Coyier ( @chriscoyier ) on CodePen .
在不知道/不固定高度的情况下
这种情况下可以通过 transform: translateY() 方法推动块状元素一半的高度来实现居中.
使用方法:
.parent { position: relative;}.child { position: absolute; top: 50%; transform: translateY(-50%);}
关于 transform: translate() 方法的补充:
translate 表示移动,该属性值含 3 种情况:translate(x,y) 水平方向和垂直方向同时移动(也就是 X 轴和 Y 轴同时移动,即斜一定角度移动);translateX(x) 仅水平方向移动(X 轴移动);translateY(Y) 仅垂直方向移动(Y 轴移动),举个例子:
transform:translateY(20px); // 表示由基点处沿垂直方向向下移动 20px
实现效果:
See the Pen Center Block with Unknown Height by Chris Coyier ( @chriscoyier ) on CodePen .
当然,也可以用flexbox实现:
.parent { display: flex; flex-direction: column; justify-content: center;}
实现效果:
See the Pen Center Block with Unknown Height with Flexbox by Chris Coyier ( @chriscoyier ) on CodePen .
水平垂直居中
固定宽高的居中方法
利用 负margin 技术实现
.parent { position: relative;}.child { width: 300px; height: 100px; padding: 20px; position: absolute; top: 50%; left: 50%; margin: -70px 0 0 -170px;}
实现效果:
See the Pen Center Block with Fixed Height and Width by Chris Coyier ( @chriscoyier ) on CodePen .
不固定/不确定高度的实现方法
可以通过两个方向都使用 transform: translate; 来实现
使用方式:
.parent { position: relative;}.child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);}
实现效果:
See the Pen Center Block with Unknown Height and Width by Chris Coyier ( @chriscoyier ) on CodePen .

WebDevelovermentReliesonHtml,CSS和JavaScript:1)HTMLStructuresContent,2)CSSStyleSIT和3)JavaScriptAddSstractivity,形成thebasisofmodernWebemodernWebExexperiences。

HTML的作用是通过标签和属性定义网页的结构和内容。1.HTML通过到、等标签组织内容,使其易于阅读和理解。2.使用语义化标签如、等增强可访问性和SEO。3.优化HTML代码可以提高网页加载速度和用户体验。

htmlisaspecifictypefodyfocusedonstructuringwebcontent,而“代码” badlyLyCludEslanguagesLikeLikejavascriptandPytyPythonForFunctionality.1)htmldefineswebpagertuctureduseTags.2)“代码”代码“ code” code code code codeSpassSesseseseseseseseAwiderRangeLangeLangeforLageforLogageforLogicIctInterract

HTML、CSS和JavaScript是Web开发的三大支柱。1.HTML定义网页结构,使用标签如、等。2.CSS控制网页样式,使用选择器和属性如color、font-size等。3.JavaScript实现动态效果和交互,通过事件监听和DOM操作。

HTML定义网页结构,CSS负责样式和布局,JavaScript赋予动态交互。三者在网页开发中各司其职,共同构建丰富多彩的网站。

HTML适合初学者学习,因为它简单易学且能快速看到成果。1)HTML的学习曲线平缓,易于上手。2)只需掌握基本标签即可开始创建网页。3)灵活性高,可与CSS和JavaScript结合使用。4)丰富的学习资源和现代工具支持学习过程。

AnexampleOfAstartingTaginHtmlis,beginSaparagraph.startingTagSareEssentialInhtmlastheyInitiateEllements,defiteTheeTheErtypes,andarecrucialforsstructuringwebpages wepages webpages andConstructingthedom。

如何设计菜单中的虚线分割效果?在设计菜单时,菜名和价格的左右对齐通常不难实现,但中间的虚线或点如何...


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

记事本++7.3.1
好用且免费的代码编辑器

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境