当我想在中心对齐内容时,自我调整不起作用

时间:2018-10-11 09:03:40

标签: html css flexbox

我必须使用自动页边距在页面中心对齐内容。

div {
  background: #121212;
  font-size: 100%;
  display: flex;
}
a {
  color: #fff;
  padding: 2%;
  display: inline-block;
  background: linear-gradient(180deg, rgba(18, 18, 18, 0.8) 0%, rgba(18, 18, 18, 0.5) 66.66%), url('https://cml.sad.ukrd.com/image/714544.png');
  background-size: cover;
  background-position: top;
  white-space: nowrap;
  font-size: 18px;
}
img {
  height: 100%;
  width: auto;
  display: flex;
  align-self: center;
  max-height: 50px;
  margin: 0 auto;
  /* fails justify-self: center; */
}
<div>
  <a href="#">⟵ Some Text Goes Here</a>
  <img src="https://cml.sad.ukrd.com/image/714824.png">
</div>

我想发现如何将块图像放置在父div的中心。 div已经有另一个<a>子级,该子级将块图像略微移出中心。 div父级是一个flexbox,我假设有一个justify-self: center规则可以工作,但显然不行,因此为什么我不得不使用margin: 0 auto呢? / p>

块图像如何位于父div的死点?

2 个答案:

答案 0 :(得分:1)

justify-self: center;是css grid的属性,而不是flex的属性。 https://css-tricks.com/snippets/css/complete-guide-grid/#prop-justify-self

答案 1 :(得分:1)

您可以从常规流程中移除a元素,使其相对于其父元素div定位。

请参见下面的演示,注释中包含文档:

div {
  background: #121212;
  font-size: 100%;
  display: flex;
  position: relative; /*Make sure the anchor tag is positioned relative to this div*/
}
a {
  color: #fff;
/*   padding: 2%; remove the padding */
  display: flex; /*Make the element a flex container to center it's contents*/
  justify-content: center;
  align-items: center;
  background: linear-gradient(180deg, rgba(18, 18, 18, 0.8) 0%, rgba(18, 18, 18, 0.5) 66.66%), url('https://cml.sad.ukrd.com/image/714544.png');
  background-size: cover;
  background-position: top;
  white-space: nowrap;
  font-size: 18px;
/* Position the element absolutely taking it out of the normal flow of the document   */
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
}
img {
  height: 100%;
  width: auto;
  display: flex;
  align-self: center;
  max-height: 50px;
  margin: 0 auto;
  /* fails justify-self: center; */
}
<div>
  <a href="#">⟵ Some Text Goes Here</a>
  <img src="https://cml.sad.ukrd.com/image/714824.png">
</div>