无论页面大小如何,我都试图将两个元素放置在给定空间的中心。
例子 https://jsfiddle.net/57q9dn78/
<div id="parent">
<div class="child right">
I am a child.
</div>
<div class="child left">
I am a child.
</div>
</div>
.child {
background-color: #ff0000;
height: 20px;
width: 100px;
max-width: 50%;
}
.right {
float: right;
margin-right: 75px;
}
.left {
float: left;
margin-left: 75px;
}
#parent {
background-color: #00FF00;
height: 20px;
padding: 20px 0;
width: 500px;
}
在示例中,#parent div 设置为 500px,其他元素的边距以此为基础。通常父级为 100% 宽度。这只是我想要的一个例子。有没有一种方法可以在 CSS 中使用 calc 或其他东西,以便随着页面大小的变化,边距的变化或完全消失取决于每个 child 都是 100px 的脸。
最佳答案
你可以使用 flexbox:
.child {
background-color: #ff0000;
height: 20px;
width: 100px;
max-width: 50%;
}
#parent {
background-color: #00FF00;
height: 20px;
padding: 20px 0;
display: flex;
justify-content: space-around;
width: 500px;
}
<div id="parent">
<div class="child right">
I am a child.
</div>
<div class="child left">
I am a child.
</div>
</div>
关于html - 响应式设计两个元素之间的自动边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35183864/