2

问题如下。我有一个块元素,比如说<div>标签,我想把它居中。我可以设置margin-left: auto; margin-right:auto,问题就会解决。但是,例如,我怎样才能使右边距比左边大两倍?

在过去的日子里,在带有框架的 HTML4.01 中,我可以将中间框架宽度设置为 600 像素,将左框架宽度设置为“1*”,将右框架宽度设置为“2*”以获得我想要的布局。那么我如何对 HTML5 做同样的事情呢?

4

4 回答 4

2

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>

http://caniuse.com/flexbox

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>
于 2013-05-24T15:01:08.963 回答
0

如果给出diva % 宽度是可以接受的,这很容易:

<!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>
于 2013-05-24T13:31:45.237 回答
0

你可以使用类似的东西:

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;值。

jsFiddle 示例

于 2013-05-24T13:32:11.270 回答
0

由于 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>
于 2013-05-24T15:59:22.837 回答