我真的很难理解 flex 是如何工作的,我的目标是这支笔
https://codepen.io/Esperteyu/pen/WMExEj
是将“在 IFrame 外单击我”按钮对齐到 iframe 的右边界,但在“下一行”中。
我可以将它与它对齐,但只是在我不将 iframe 容器居中时,如果这有意义的话。理想情况下,我希望 iframe 居中并且按钮与其右侧对齐。
html 是:
<div class="container">
<div class="container-center ">
<div class="center ">
<iframe srcdoc="<html><body><h2 style='text-align:center'>This is the iframe</h2><input type='button' value='Click Me Inside the iframe' style='float: right;'></body></html>">
</iframe>
</div>
</div>
<div class="container-right">
<div class="right">
<div>
<input type="button" value="Click Me Outside of the iframe">
</div>
</div>
</div>
</div>
CSS 是:
.container {
background:red;
}
.container-center {
display:flex;
justify-content: center;
flex-direction: row;
width:100%;
}
.container-right {
display:flex;
justify-content: flex-end;
flex-direction: row;
}
.center {
display: flex;
background: lightblue;
}
.center iframe{
width: 100%;
}
有什么帮助吗?
谢谢
最佳答案
要让 container-center
以其父级为中心,并且由于 Flexbox 没有自己的属性来实现这一点,您可以寻求一些帮助,例如伪,以匹配 right
元素,并使 container
成为 flex 容器。
.container {
background:red;
display:flex;
justify-content: center;
}
.container-right,
.container::before {
content: '';
flex: 1;
}
使用 flex: 1
,伪和 container-right
将占用相等的剩余空间,并插入 container-center
到中间,并通过 container-right
上的 align-items
控制其子项的垂直对齐方式。
如果你 check this codepen ,我在伪/右元素上添加了边框,你会更清楚地看到发生了什么。
堆栈片段
.container {
background:red;
display:flex;
justify-content: center;
}
.container-right,
.container::before {
content: '';
flex: 1;
}
.container-center {
}
.container-right {
display:flex;
align-items: flex-end; /* align children vertically */
overflow: hidden;
}
.center {
display: flex;
background: lightblue;
}
.center iframe{
width: 100%;
}
<div class="container">
<div class="container-center ">
<div class="center ">
<iframe srcdoc="<html><body><h2 style='text-align:center'>This is the iframe</h2><input type='button' value='Click Me Inside the iframe' style='float: right;'></body></html>">
</iframe>
</div>
</div>
<div class="container-right">
<div class="right">
<div>
<input type="button" value="Click Me Outside of the iframe">
</div>
</div>
</div>
</div>
根据评论更新。
如果您的意思是 frame 外的按钮应该在其自身的一行上右对齐,则您需要一个额外的包装器来实现这一点。
堆栈片段
.container {
background:red;
display:flex;
justify-content: center;
}
.container-right {
display:flex;
justify-content: flex-end;
}
.center {
display: flex;
background: lightblue;
}
.center iframe{
width: 100%;
}
<div class="container">
<div class="wrapper">
<div class="container-center ">
<div class="center ">
<iframe srcdoc="<html><body><h2 style='text-align:center'>This is the iframe</h2><input type='button' value='Click Me Inside the iframe' style='float: right;'></body></html>">
</iframe>
</div>
</div>
<div class="container-right">
<div class="right">
<div>
<input type="button" value="Click Me Outside of the iframe">
</div>
</div>
</div>
</div>
</div>
请注意,最后一个示例的代码可以简化为: https://codepen.io/anon/pen/ddzNgy
关于html - 使用 flex 将按钮对齐到同级的右侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48773048/