带有额外空格的自动补距

问题描述 投票:0回答:3

是否有一种方法可以通过margin自动使页面中的元素水平居中,但是如果视口变小,则可以左右100px,所以在一起就像这样:

margin: 0 auto;
margin-left:100px;
margin-right:100px;

或者我是否需要为此使用父容器?

css margin centering
3个回答
0
投票

您可以使用border-leftborder-right在元素的左侧和右侧添加边框。确保将边框颜色设置为transparent并添加background-clip: padding-box以确保边框真正不可见:

.centered {
  margin: 0 auto;
  width: 100px;
  height: 100px;
  background: blue;
  background-clip: padding-box;
  border-left: 100px solid transparent;
  border-right: 100px solid transparent;
}
<div class="centered"></div>

另一种方法是将父元素与padding一起使用:

.parent {
  padding: 0 100px;
}
.centered {
  margin: 0 auto;
  width: 100px;
  height: 100px;
  background: blue;
}
<div class="parent">
  <div class="centered"></div>
</div>

根据您的用例,您也许可以使用<body>作为父元素,从而避免添加多余的父元素:

body {
  padding: 0 100px;
}
.centered {
  margin: 0 auto;
  width: 100px;
  height: 100px;
  background: blue;
}
<div class="centered"></div>

0
投票

auto的问题是您甚至不能在calc(auto + 100px)中使用它

最准确,最准确的方法是使用flex

justify-content属性会将您的元素居中放置在margin: 0 auto;的位置,并且您仍然有一个可以玩margin的空间

.parent{
    height: 200px;
    background: gray;
    display:flex;
    justify-content:center; /*center element*/ 
 
}

.child{
   height: 100px;
   width: 200px;
   background: yellow;
   margin: 0 100px; /*adding margin*/ 
}
<div class='parent'>
    <div class="child"></div>
</div>

-1
投票

您可以为此使用填充

© www.soinside.com 2019 - 2024. All rights reserved.