【发布时间】:2016-12-27 01:17:46
【问题描述】:
我一直在阅读 flex-boxes 以解决我一直遇到的问题。我读过的关于/用作问题研究的主要文章是this。
我最近在this 和this 问题中提出了这个主题,并且感谢@Michael_B 的帮助,解决了如何将元素(在本例中为<h2>)居中在一个flex -box,只要弹性盒中总是且只有三个弹性项目(在此布局中:<div><h2><div>)。
我想扩展这些点,因为我意识到如果弹性项目总数超过或(更实际地)少于 3 个,可能会有一个解决方案。
它涉及使用边距。如果你在一个弹性项目上使用margin: auto;,它的作用是使项目在主轴上居中(参见下图了解弹性盒的工作原理)。
img {
width: 100%;
height: 100%;
}
<img src="http://i.stack.imgur.com/9Oxw7.png" alt="flex-box demo" />
(这是我能想出如何获取下拉照片的最佳方法...)
据我了解,使用margin: auto 是当前对应于交叉轴的align-selfproperty。
因此,可以通过以下方式在弹性框中将弹性项目居中:
$(document).on('click', 'button', function(e) {
$this = $(this);
if ($this.attr('id') === 'button1') {
$('h2').parent().attr("class", "");
$('h2').attr("class", "toggle1");
}
if ($this.attr('id') === 'button2') {
$('h2').parent().attr("class", "");
$('h2').attr("class", "toggle1");
}
if ($this.attr('id') === 'button3') {
$('h2').parent().attr("class", "toggle3");
$('h2').attr("class", "");
}
if ($this.attr('id') === 'button4') {
$('h2').parent().attr("class", "toggle4");
$('h2').attr("class", "");
}
if ($this.attr('id') === 'button0') {
$('h2').parent().attr("class", "");
$('h2').attr("class", "");
}
});
div:not(.cont),
div:not(.cont) * {
border: 1px dotted red;
}
div {
align-items: center;
display: flex;
}
button {
margin: 16px;
}
.toggle1 {
margin: auto;
}
.toggle2 {
flex: 1;
}
.toggle3 {
justify-content: center;
}
.toggle4 {
justify-content: space-between;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div>
<h2>I'm an h2</h2>
</div>
<div>
<span>I'm a span!</span>
<h2>I'm an h2</h2>
<span>I'm a span!</span>
</div>
<div>
<span>I'm a span!</span>
<span>I'm a span!</span>
<h2>I'm an h2</h2>
<span>I'm a span!</span>
<span>I'm a span!</span>
</div>
<div class="cont">
<button id="button0">clear</button>
<button id="button1">margins</button>
<button id="button2">flex-grow</button>
</div>
<div class="cont">
<button id="button3">justify-content: center
<br />(on parent)</button>
<button id="button4">justify-content: space-around
<br />(on parent)</button>
</div>
从上面的 sn-p 中可以看出,它只有在 <h2> 的每一侧都有相同数量的 flex-items 时才有效(您还可以看到 justify-content: space-around 不适用于 just一个对象)。
但是,如果您要居中的对象的每一侧都有数量不平衡的 flex 项目怎么办? - 当然,您可以将空白元素放在那里并使用
flex: 1;,但那看起来有点hacky。
我的想法是利用负边距。我读了一篇很棒的文章 (here) 关于使用负边距以及它们如何将对象拉向它们等等(另外,甚至 w3 说它们是合法代码 - 不是 hacky)。
我们的想法是将<h2> 设置为margin: auto;,然后以某种方式(我强调不知何故,就像我一直在做的所有研究一样,我开始失去希望......)任何同级 flex-item 的宽度并从 <h2> margin: auto;... 中否定它听起来很老套,希望有一种方法可以在没有 JS/jQuery 或 CSS 编译器的情况下做到这一点。
有没有人知道一种方法可以从弹性项目的边缘否定同一个弹性盒子中同级弹性项目的宽度?
谢谢。
附注/更新
可能有一种方法可以使用position 属性来完成此操作;然而,我所做的所有测试都没有产生任何结果......也许其他人已经用这种方法成功了?
【问题讨论】:
-
如果 Michael_B 不知道...那么没人知道...
-
@Paulie_D,或者我正在工作,现在无法进入 :-)
-
不管怎样,我经常看到你(和@Oriol)处理比这更复杂的问题。
-
可能,但整个问题是基于做一些 flexbox 不打算做的事情。这不是解决任何和所有布局问题的灵丹妙药。 Javascript 存在是有原因的...进行 CSS 并非旨在执行的那种计算。
-
你到底想做什么?
标签: javascript jquery html css flexbox