问题如下。我有一个块元素,比如说<div>
标签,我想把它居中。我可以设置margin-left: auto; margin-right:auto
,问题就会解决。但是,例如,我怎样才能使右边距比左边大两倍?
在过去的日子里,在带有框架的 HTML4.01 中,我可以将中间框架宽度设置为 600 像素,将左框架宽度设置为“1*”,将右框架宽度设置为“2*”以获得我想要的布局。那么我如何对 HTML5 做同样的事情呢?
This isn't a great solution as it requires Flexbox and one extra element, but the right "margin" is twice as large as the left "margin":
http://codepen.io/cimmanon/pen/agFzw
.foo {
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
/* fix for old Firefox */
width: 100%;
}
.bar {
border: 1px solid;
width: 600px;
/* optional */
-webkit-box-flex: 0;
-moz-box-flex: 0;
-webkit-flex: 0 1 600px;
-ms-flex: 0 1 600px;
flex: 0 1 600px;
}
.foo:after {
-webkit-box-flex: 2;
-moz-box-flex: 2;
-webkit-flex: 2;
-ms-flex: 2;
flex: 2;
display: block;
content: ' ';
}
.foo:before {
-webkit-box-flex: 1;
-moz-box-flex: 1;
-webkit-flex: 1;
-ms-flex: 1;
flex: 1;
display: block;
content: ' ';
}
<div class="foo">
<div class="bar">
Bar
</div>
</div>
If you're ok with 3 extra elements, you can use display: table/table-cell
and maximize your browser support:
http://cssdeck.com/labs/saojg66o
.foo {
display: table;
width: 100%;
}
.a, .b, .c {
display: table-cell;
}
.a {
width: 10%;
}
.b {
border: 1px solid;
width: 600px;
}
.c {
width: 20%;
}
<div class="foo">
<div class="a">
</div>
<div class="b">
Foo
</div>
<div class="c">
</div>
</div>
如果给出div
a % 宽度是可以接受的,这很容易:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
div {width: 40%; height: 600px; background: red; margin-left: 20%; margin-right: 40%;}
</style>
</head>
<body>
<div></div>
</body>
</html>
你可以使用类似的东西:
div {
position: absolute;
width: 300px; height: 300px;
top: 50%; left: 50%;
margin-top: -150px; margin-left: -150px;
border: 1px solid black
}
这将集中<div>
你所说的。如果您想要更多或更少的左边距或右边距,只需更改margin-left: -150px;
值。
由于 div 必须具有固定宽度,因此可能需要 JS 来实现这一点。我是 JS 新手,所以这可能是糟糕的代码,但它似乎可以完成这项工作,无论如何:http ://cdpn.io/LIizc
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
body {margin: 0; padding: 0;}
div {width: 600px; height: 600px; background: red; }
</style>
</head>
<body>
<div id="test"></div>
<script>
function resize(elem){
var windowWidth = document.documentElement.clientWidth,
remainder = windowWidth - elem.clientWidth;
elem.style.marginLeft = remainder * 1/3 + "px";
}
var div = document.getElementById("test");
window.addEventListener('resize', function(){
resize(div);
}, false);
resize(div);
</script>
</body>
</html>