我有 5 个 div,左浮动和行内 block 对齐。我想移出其中的一个 div 并将其居中放置在页面中间。
我尝试重置 float 并设置绝对位置,但 div 没有居中(仍在页面右侧)。
如果重置位置(相对),div 正确居中,但其他 div 移动到页面底部(我不明白为什么)。
* {
margin: 0;
padding: 0;
}
body {
background-color: #00ced1;
}
/* Box */
.box {
background-color: #ff0000;
border: .250rem solid #fff;
color: white;
cursor: pointer;
display: block;
float: left;
font-family: segoe ui;
margin: 1.5% 1%;
padding: 1rem;
text-align: center;
transition: position .35s ease-in,
margin .35s ease-in,
width .35s ease-in,
transform .35s ease-in;
}
.box:hover {
background-color: #20b2aa;
}
.box:nth-child(1) {
display: block;
float: none;
position: relative;
width: calc(100/4- 2*1rem - 2*1% - 2*.250rem);
margin: 200px auto;
}
/* Width of the boxes */
.width {
width: calc(100%/4 - 2*1rem - 2*1% - 2*.250rem);
}
这是 jsFiddle 上的示例:http://jsfiddle.net/035j1s90/1/
谢谢。
最佳答案
如果我没记错的话,你要居中一个<div>
在中间并放置其他四个<div>
就在它的正下方。居中的 div 和四个 div 之间的巨大差距是因为 margin: 200px auto
您在 CSS 中为 .box:nth-child(1)
指定的属性.只需将其更改为 margin: 0px auto 0px auto
这样你的布局就可以了,就像这样:
* {
margin: 0;
padding: 0;
}
body {
background-color: #00ced1;
}
/* Box */
.box {
background-color: #ff0000;
border: .250rem solid #fff;
color: white;
cursor: pointer;
display: block;
float: left;
font-family: segoe ui;
margin: 1.5% 1%;
padding: 1rem;
text-align: center;
transition: position .35s ease-in,
margin .35s ease-in,
width .35s ease-in,
transform .35s ease-in;
}
.box:hover {
background-color: #20b2aa;
}
.box:nth-child(1) {
display: block;
float: none;
position: relative;
width: calc(100/4- 2*1rem - 2*1% - 2*.250rem);
margin: 0px auto 0px auto;
}
/* Width of the boxes */
.width {
width: calc(100%/4 - 2*1rem - 2*1% - 2*.250rem);
}
<div class="box width">Translate</div>
<div class="box width">Rotate</div>
<div class="box width">Scale</div>
<div class="box width">Skew</div>
<div class="box width">Matrix</div>
更新:
我稍微修改了您的 HTML 结构。 <div class="box width">Translate</div>
你想要居中的那个已经移到了你的 HTML 的末尾,我把它放在了 <div id="centered"><div>
里面。 .
* {
margin: 0;
padding: 0;
}
body {
background-color: #00ced1;
}
/* Box */
.box {
background-color: #ff0000;
border: .250rem solid #fff;
color: white;
cursor: pointer;
display: block;
float: left;
font-family: segoe ui;
margin: 1.5% 1%;
padding: 1rem;
text-align: center;
transition: position .35s ease-in, margin .35s ease-in, width .35s ease-in, transform .35s ease-in;
}
.box:hover {
background-color: #20b2aa;
}
#centered {
text-align: center;
}
#centered .box {
display: inline-block;
float: none;
}
/* Width of the boxes */
.width {
width: calc(100%/4 - 2*1rem - 2*1% - 2*.250rem);
}
<div class="box width">Rotate</div>
<div class="box width">Scale</div>
<div class="box width">Skew</div>
<div class="box width">Matrix</div>
<div id="centered">
<div class="box width">Translate</div>
</div>
关于html - 从内联 block div 组移出并居中一个 div, float 左对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26498611/