我一直在研究flex-box以解决我遇到的问题。我阅读的主要文章是这篇文章。
最近我在这里和这里提出了这个话题,感谢@Michael_B的帮助,我们找到了如何将某个元素(在本例中为<h2>
)居中放置在flex-box中,只要flex-box中始终且仅有三个flex-item(在此布局中:<div><h2><div>
)。
我想扩展这些观点,因为我意识到可能有一种解决方案,即使总共的flex-item数量不到3个或者大于3个也可以解决。
它涉及使用外边距。如果您在一个flex-item上使用margin: auto;
,它会在主轴上居中一个项(请参见以下图片了解flex-box的工作原理)。
img {
width: 100%;
height: 100%;
}
<img src="http://i.stack.imgur.com/9Oxw7.png" alt="flex-box demo" />
那是我能想到的最好方法,可以实现一个下拉式照片......
从我的理解来看,使用 margin: auto
是当前在交叉轴上与 align-self
属性相对应的方式。
因此,可以通过以下方式之一来使 flex 盒中的 flex 项居中:
$(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>
从上面的代码段中可以看出,它只能在每个<h2>
两侧有相同数量的伸缩项时起作用(并且您还可以看到justify-content: space-around
不能与一个对象一起使用)。
但是,如果在您尝试居中的对象的两侧存在不平衡数量的伸缩项怎么办? - 当然,您可以在那里放置空元素并使用
flex: 1;
,但这似乎有点粗糙。
我的想法是利用负边距。我读了一篇很棒的文章(点击此处),介绍了如何使用负边距以及它们如何将对象拉向它们等内容。(而且,连w3也表示它们是合法的代码-不是粗糙的代码)。
思路是将<h2>
设置为margin: auto;
,然后以某种方式(我强调用所有我一直在做的研究都开始失去希望)从同一伸缩盒中的任何兄弟伸缩项中取出宽度并将其从<h2> margin: auto;
中去除...听起来很粗糙,但希望有一种方法可以在不使用JS / jQuery或CSS编译器的情况下完成它。
是否有人知道如何从同一伸缩盒中的兄弟伸缩项中减去另一个伸缩项的宽度?
谢谢。
P.S./更新
也许可以使用position
属性来实现这一点;但是,我所做的所有测试都没有产生结果...也许其他人已经成功使用了这种方法?