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] 第257天 如何让一个块元素绝对居中? #1707

Open
haizhilin2013 opened this issue Dec 28, 2019 · 3 comments
Open

[css] 第257天 如何让一个块元素绝对居中? #1707

haizhilin2013 opened this issue Dec 28, 2019 · 3 comments
Labels
css css

Comments

@haizhilin2013
Copy link
Collaborator

第257天 如何让一个块元素绝对居中?

作者:一条有梦想的鱼

我也要出题

@haizhilin2013 haizhilin2013 added the css css label Dec 28, 2019
@huanhuan13754
Copy link

div{
position:fixed;
right:0;
left:0;
bottom:0;
top:0;
margin: auto auto
}

@kun-qi
Copy link

kun-qi commented May 11, 2021

.center{
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: grid;
place-items: center;
}

@Wyt-GitHub8000
Copy link

要让一个块元素绝对居中,可以使用以下方法:

使用绝对定位和负边距
将要居中的块元素设置为绝对定位,然后使用负边距将它居中。需要设置父元素的宽度和高度,并且要使用相对定位或者绝对定位。

.parent {
position: relative;
width: 400px;
height: 400px;
}

.child {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
margin-top: -100px;
margin-left: -100px;
}
使用绝对定位和 transform 属性
将要居中的块元素设置为绝对定位,然后使用 transform 属性将它居中。需要设置父元素的宽度和高度,并且要使用相对定位或者绝对定位。

.parent {
position: relative;
width: 400px;
height: 400px;
}

.child {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
transform: translate(-50%, -50%);
}
使用 flex 布局
将父元素设置为 flex 布局,并设置子元素的 margin 属性为 auto。需要设置父元素的宽度和高度。

.parent {
display: flex;
justify-content: center;
align-items: center;
width: 400px;
height: 400px;
}

.child {
width: 200px;
height: 200px;
margin: auto;
}
以上是几种常见的让一个块元素绝对居中的方法,你可以根据具体的需求和业务逻辑进行选择和调整。需要注意的是,不同的方法可能会对布局和性能产生不同的影响,需要根据实际情况进行权衡和选择。

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

No branches or pull requests

4 participants