【发布时间】:2016-09-12 05:08:18
【问题描述】:
假设父级是相对的,子级(style-x)是绝对的。我用前 50%,剩下的 25% 让孩子居中。
我希望实际上将孩子居中,所以我设置了 transform: translate(-50%, -50%)。我不确定这是否居中,所以我通过删除该行并添加'margin-top:-55px;'来仔细检查(高度的一半)和'margin-left:-45px;' (宽度的一半)。
这两行将我的元素定位在稍微不同的位置,但这与我的 CSS 模型不同。怎么回事?
body {
height: 100%;
width: 100%;
margin: 0 auto;
}
#main {
overflow: auto;
height: 64vh;
width: 38vw;
margin: 0 auto;
margin-top: 10%;
position: relative;
border: 1vh solid black;
overflow: hidden;
}
#style-x {
/*Why doesn't translate(-50%, -50%) give me
the same position as setting the margin top and
left to half of the width and height?*/
width: 90px;
height: 110px;
/*
transform: translate(-50%, -50%);*/
margin-top: -55px;
margin-left: -45px;
position: absolute;
top: 50%;
left: 25%;
padding: 2%;
text-align: center;
background: green;
}
#left-col {
float: left;
width: 4%;
height: 101%;
margin-left: 46%;
background: black;
}
#right-col {
float: left;
width: 4%;
height: 101%;
margin: 0 auto;
margin-left: 0;
background: black;
}
<body>
<section id='main'>
<div id='style-x'>X</div>
<div id='left-col'></div>
<div id='right-col'></div>
</section>
</body>
如果您想要可视化,这是我的 Codepen。
【问题讨论】:
-
所以您希望
style-x在section中水平和垂直居中?只需删除边距并添加您拥有的translate并使left50% -
你没有粘贴 codepen 链接
-
谢谢,已修复。为什么要删除边距?为什么不把翻译拿出来?我想把它放在部分的左半部分。
标签: css