我正在尝试解决这个布局难题,但一直纠结于如何让它优雅、干净和永恒。
给定:
- 一条 1 像素高的水平线在容器内延伸
- 这条线上垂直和水平居中的框
- 一个左对齐的文本框
- 和一个右对齐的文本框
我尝试过的是,痛苦地增加百分比,直到我达到某种中间...警告,免责声明,以下代码非常图形化且丑陋!
CSS
author{color: grey}
box{float: left;
background: blue;
margin: 0 0 0 46.4%;
...
/* bad coding feel embarrassed showing this */
}
time{color: grey}
HTML(灵活,如有需要请更改)
<author></author>
<box><img src=""/></box>
<time></time>
我首先想到这可能会在 flexbox 中解决,使用 justify-content: space-between
但是,我不知道如何使该行出现在那里。所以我愿意接受任何建议,无论是好的旧定位/ float 还是使用 flexbox。也许尝试用两种方法解决它并看看哪种方法最优雅会更好?提前致谢!
最佳答案
这是实现这一点的一种方法,您可以使用 justify-content: space-between
来对齐 author
/box
/date
和一个绝对定位的伪元素来画线
#wrapper {
position: relative;
display: flex;
justify-content: space-between;
}
#wrapper::before {
content: '';
position: absolute;
left: 0; right: 0;
top: 50%; height: 1px;
background: gray;
}
#wrapper > * {
position: relative; /* instead of 'z-index: -1' on the pseudo so
the line stays below the items */
}
#author {}
#date {}
#box {
width: 50px;
height: 50px;
background: blue;
}
<div id="wrapper">
<div id="author">
Author
</div>
<div id="box">
</div>
<div id="date">
Date
</div>
</div>
根据评论更新
在这种情况下,#wrapper > *
规则可以替换为在 box
上设置 position: relative
,我推荐这样做给它一个 z-index
。
根据第二条评论更新
由于组合 Flexbox/script 有问题,这里有一个版本没有,但具有相同的标记和几乎一样短的 CSS
#wrapper {
position: relative;
}
#wrapper::before {
content: '';
position: absolute;
left: 0; right: 0;
top: 50%; height: 1px;
background: gray;
}
#author {
position: absolute;
top: 0;
left: 0;
}
#date {
position: absolute;
top: 0;
right: 0;
}
#box {
position: relative;
margin: 0 auto;
width: 50px;
height: 50px;
background: blue;
}
<div id="wrapper">
<div id="author">
Author
</div>
<div id="box">
</div>
<div id="date">
Date
</div>
</div>
关于css - 布局拼图 : align to Left AND Right plus a Centered box All connected with a Line,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46422175/