有没有办法仅使用 CSS
将一个 div
水平居中并向右移动x像素?
我现在有这些CSS代码:
#mydiv {
display: block;
width: 200px;
margin: 200px auto;
}
我想将这个div定位到中心位置再向右移动300像素。是否可以只使用CSS实现?
(我知道有一种使用jQuery的方法,请参考此处,但我希望只使用CSS实现。)
有没有办法仅使用 CSS
将一个 div
水平居中并向右移动x像素?
我现在有这些CSS代码:
#mydiv {
display: block;
width: 200px;
margin: 200px auto;
}
#mydiv
上添加 transform: translateX(300px);
来实现这一效果。#mydiv {
display: block;
width: 200px;
margin: 200px auto;
transform: translateX(300px);
}
calc()
函数实现。#mydiv {
display: block;
width: 200px;
margin-left: calc(50% + 200px); /* 50% - 100px (half of the div) + 300px */
}
#mydiv {
display: block;
width: 200px; height: 50px;
margin-left: calc(50% + 200px);
/* 50% - 100px (half of the div) + 300px */
background: blue;
}
<div id="mydiv"></div>
.container
)上方放置一个大小为0X0像素的.wrapper
元素,并在此包装器内定位您的.content
并调整其'offset'(right
/left
属性)。<div class="container">
<div class="anchor">
<div class="content"></div>
</div>
</div>
.container {
background-color:red;
position:relative;
height:500px;
}
.anchor {
position:absolute;
top:50%;
left:50%;
width:0;
height:0;
overflow:visible;
}
.content{
position:absolute;
right:-100px; /* play with this to shift the content from the center... */
width:200px;
height:50px;
background-color:blue;
}
像这个例子:https://jsfiddle.net/j6rnvdzp/?
div {
display: block;
width: 200px;
margin: 200px auto;
background-color:red;
position:absolute;
right:-300px;
left:0;
}