html - tip - 标签title
元素不会保持中心,特别是在重新调整屏幕时 (2)
您可以使用新的CSS3 calc()
函数,它允许您进行算术计算中心点。
要得到您的中心点,计算将必须是:
50% - (56px / 2)
所以这样最终就是这样
50% - 28px
把它放在calc()
函数中,然后在浏览器中找出它并将其完美地放在中心。
body {
background: #333333;
}
.container {
width: 98%;
height: 80px;
line-height: 80px;
position: relative;
top: 20px;
min-width: 250px;
margin-top: 50px;
}
.container-decor {
border: 4px solid #C2E1F5;
color: #fff;
font-family: times;
font-size: 1.1em;
background: #88B7D5;
text-align: justify;
}
.container:before {
top: -33px;
left: calc(50% - 28px);
transform: rotate(45deg);
position: absolute;
border: solid #C2E1F5;
border-width: 4px 0 0 4px;
background: #88B7D5;
content: '';
width: 56px;
height: 56px;
}
<div class="container container-decor">great distance</div>
我的问题是我不能水平地中心一个三角形指针。
那么我可以把指针放在一些窗口大小的中心位置,但是当我收缩或扩大窗口时,它会将它放在错误的地方。
我失踪了什么
body {
background: #333333;
}
.container {
width: 98%;
height: 80px;
line-height: 80px;
position: relative;
top: 20px;
min-width: 250px;
margin-top: 50px;
}
.container-decor {
border: 4px solid #C2E1F5;
color: #fff;
font-family: times;
font-size: 1.1em;
background: #88B7D5;
text-align: justify;
}
.container:before {
top: -33px;
left: 48%;
transform: rotate(45deg);
position: absolute;
border: solid #C2E1F5;
border-width: 4px 0 0 4px;
background: #88B7D5;
content: '';
width: 56px;
height: 56px;
}
<div class="container container-decor">great distance</div>
你的箭头以left:48%
为中心left:48%
。 这可以根据箭头元素的左边缘将箭头定位在容器中心附近 。
换句话说,假设你使用left:50%
(这是正确的方法),这不会使容器中的箭头元素居中。 它实际上将元素的左边缘居中在容器中。
在下面的图像中,使用text-align:center
在页面上text-align:center
。
为了进行比较,请查看以left:50%
为中心的箭头left:50%
。
元素位于中间右侧。 随着窗口变小,这种偏差变得更加明显。
因此,通常看到集中的,绝对定位的元素使用transform
属性:
.triangle {
position: absolute;
left: 50%;
transform: translate(-50%,0);
}
transform
规则告诉三角形将其自身移回其宽度的50%。 这使它完美地集中在线上。 现在它模拟text-align:center
。
在translate(-50%,0)
,第一个值指向x轴(水平),另一个值适用于y轴。 一个等价的规则是transform:translateX(-50%)
(还有transform:translateY()
)。
另外,以下是使用以下方法水平和垂直放置元素的方法:
.triangle { position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); }
注意:如果您使用
right: 50%
或bottom: 50%
,则各自的translate
值将为50%
(不是负数) 。
然而,在这个特殊问题中,出现一个问题是因为transform:rotate(45deg)
也在声明块中。 添加第二个transform
意味着第一个transform
被忽略(按级联)。
所以,作为一个解决方案,请尝试:
.container::before {
left: 50%;
transform: translate(-50%,0) rotate(45deg);
}
通过将功能链接在一起,可以应用多种功能。
只要注意订单重要。 如果translate
和rotate
反转,三角形将首先旋转45度,然后沿着旋转的轴移动-50%,从而打破布局。 所以请确保translate
首先。 (感谢@Oriol在评论中指出这一点。)
以下是完整的代码:
body {
background: #333333;
}
.container {
width: 98%;
height: 80px;
line-height: 80px;
position: relative;
top: 20px;
min-width: 250px;
margin-top: 50px;
}
.container-decor {
border: 4px solid #C2E1F5;
color: #fff;
font-family: times;
font-size: 1.1em;
background: #88B7D5;
text-align: justify;
}
.container::before {
top: -33px;
left: 50%;
transform: translate(-50%,0) rotate(45deg);
position: absolute;
border: solid #C2E1F5;
border-width: 4px 0 0 4px;
background: #88B7D5;
content: '';
width: 56px;
height: 56px;
}
<div class="container container-decor">great distance</div>