gpt4 book ai didi

css - float 中心或边缘 : 0 auto; some problems

转载 作者:行者123 更新时间:2023-11-28 12:52:32 25 4
gpt4 key购买 nike

我希望我的按钮中心位于主 div 中。我想我写错了一些位置元素。你能帮我解决这个问题吗? Fiddle

<div class='main'>
<div class='button'>Click me</div>
</div>

.main{
width:80%;
height:300px;
background:#ddd;
margin:0 auto;
position:relative;
}

.button{
padding: 10px 12px;
background:#999;
width:90px;
margin: 50px auto;
position: absolute;
color:#fff;
}

最佳答案

首先,去掉绝对定位。然后您会注意到顶部/底部边距不起作用。这是因为垂直 margins are collapsing :

Box Model 8.3.1 Collapsing margins

In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.

When two or more margins collapse, the resulting margin width is the maximum of the collapsing margins' widths. In the case of negative margins, the maximum of the absolute values of the negative adjoining margins is deducted from the maximum of the positive adjoining margins. If there are no positive margins, the maximum of the absolute values of the adjoining margins is deducted from zero.

解决此问题的一种方法是将overflow:hidden 添加到父元素.main。这将建立一个 new block formatting context .

Updated Example

.main {
width:80%;
height:300px;
background:#ddd;
margin:0 auto;
position:relative;
overflow:hidden;
}
.button {
padding: 10px 12px;
background:#999;
width:90px;
margin: 50px auto;
color:#fff;
}

关于css - float 中心或边缘 : 0 auto; some problems,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23447213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com