将最大宽度居中的div设为无边距:auto;

时间:2016-03-01 11:25:09

标签: html css html5 css3

这是我的笔:http://codepen.io/helloworld/pen/oxgqpJ

我想将具有固定最大宽度的div居中,但是当我处于固定的最大宽度之下时,我希望每边的边距为10%,因为此刻在该分辨率区域中没有可见的边距。 / p>

缺点是在每侧使用10%的余量,div不再居中,而是从左侧开始......

我该如何解决?

<div id="container">
  Center me with a fixed max width, but when I am under the fixed max width I want a margin of 10% on each side , because at the moment there is no visible margin.
</div>



#container
{
  margin: 0 auto;

  // use instead in smaller resolutions
  //margin: 0 10%;
  max-width:1024px;
  background:orange;
}

3 个答案:

答案 0 :(得分:2)

您可以使用此功能,例如:

@media (max-width: 1024px) {
    #container { margin: 0 10%; }
}

请参阅http://www.w3schools.com/cssref/css3_pr_mediaquery.asp

答案 1 :(得分:1)

我不太确定我完全理解你的问题,但也许这样做 我只是使用保证金确保它居中,然后填充以确保任何一方的10%。
显然这意味着它只满足你对div(文本)的实际内容的要求,而不是div本身,但是再次;也许这还不错?

#container
{
  max-width:1024px;
  margin: auto;
  padding-left: 10%;
  padding-right: 10%;
  background:orange;
}

答案 2 :(得分:0)

您必须依赖Media Query在不同条件下为同一对象应用不同的边距。除了您创建的课程外,请应用此

@media only screen and (max-width: 1024px) {
/* For mobile phones: */
  #container {
     margin:0 10%;
  }
}

在其他更高的屏幕中,将应用其他css属性! 了解如何使用媒体查询:http://www.w3schools.com/css/css_rwd_mediaqueries.asp