Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Justify-self is not working when I want to align content in the center [duplicate]

Tags:

html

css

flexbox

I am having to use auto margins to align content in the center of the page.

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>

I want to discover how to position the blocks image in the centre of the parent div. The div already has another <a> child, which is pushing the block image slightly out of the centre. The div parent is a flexbox, and I assumed having a justify-self: center rule would work, but apparently not, hence why I've had to use margin: 0 auto, which doesn't competely centre align it anyway.

How can the block image be in the dead centre of the parent div?

like image 937
user8758206 Avatar asked Dec 10 '25 17:12

user8758206


2 Answers

justify-self: center; is a property of css grid, not flex. https://css-tricks.com/snippets/css/complete-guide-grid/#prop-justify-self

like image 132
Girisha C Avatar answered Dec 12 '25 09:12

Girisha C


You could take the a element out of normal flow positioning it relative to it's parent div.

See below for a demo and the documentation is in the comments:

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>
like image 23
Danny Avatar answered Dec 12 '25 11:12

Danny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!