Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【资源帖】CSS居中实现 #420

Open
zptcsoft opened this issue Sep 7, 2018 · 3 comments
Open

【资源帖】CSS居中实现 #420

zptcsoft opened this issue Sep 7, 2018 · 3 comments

Comments

@zptcsoft
Copy link
Collaborator

zptcsoft commented Sep 7, 2018

稍后整理,有激情的同学可以代为整理,赠送平时成绩30分。

@nixiaoliang
Copy link

一、对于行内元素:

text-align:center;

二、对于确定宽度的块级元素:

(1)margin和width实现水平居中

常用(前提:已设置width值):margin-left:auto; margin-right:auto;

(2)绝对定位和margin-left: -(宽度值/2)实现水平居中

固定宽度块级元素水平居中,通过使用绝对定位,以及设置元素margin-left为其宽度的一半

.content{

width: 200px;

position: absolute;

left: 50%;

margin-left: -100px; // 该元素宽度的一半,即100px

background-color: aqua;

}

(3)position:absolute + (left=0+top=0+right=0+bottom=0) + margin:auto

.content{

position: absolute;

width: 200px;

top: 0;

right: 0;

bottom: 0;

left: 0;

margin: auto;

}

三、对于未知宽度的块级元素:

(1)table标签配合margin左右auto实现水平居中

使用table标签(或直接将块级元素设值为display:table),再通过给该标签添加左右margin为auto

(2)inline-block实现水平居中方法

display:inline-block;(或display:inline)和text-align:center;实现水平居中

存在问题:需额外处理inline-block的浏览器兼容性(解决inline-block元素的空白间距)

(3)绝对定位实现水平居中

绝对定位+transform,translateX可以移动本省元素的50%
.content{

position: absolute;

left: 50%;

transform: translateX(-50%); /* 移动元素本身50% */

background: aqua;

}

(4)相对定位实现水平居中

用float或者display把父元素变成行内块状元素
.contentParent{

display: inline-block; /* 把父元素转化为行内块状元素 */

/*float: left; 把父元素转化为行内块状元素 */

position: relative;

left: 50%;

}

/目标元素/

.content{

position: relative;

right: 50%;

background-color:aqua;

}

(5)CSS3的flex实现水平居中方法,法一

.contentParent{

display: flex;

flex-direction: column;

}

.content{

align-self:center;

}

(6)CSS3的flex实现水平居中方法,法二

.contentParent{

display: flex;

}

.content{

margin: auto;

}

(7)CSS3的fit-content配合左右margin为auto实现水平居中方法

.content{

width: fit-content;

margin-left: auto;

margin-right: auto;

}

@FullOfVigour
Copy link

推荐一个很好用的属性:display:flex;

@zptcsoft
Copy link
Collaborator Author

zptcsoft commented Sep 12, 2018

推荐一个很好用的属性:display:flex;

@FullOfVigour 感谢师兄的参与,flexbox确认是一个强大的属性。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants