Home > Net >  Why is margin: 0 0 0 auto not working without display: flex?
Why is margin: 0 0 0 auto not working without display: flex?

Time:01-15

Using the below code, I am trying to take the Follow button at the right of the screen. For that, I am using margin: 0 0 0 auto for the .follow class. It works when I use display: flex in the parent element (here is header element), but when I remove display: flex from the parent, it comes down my name. Why is it happening?

header {
  display: flex;
  font-family: Montserrat, monospace;
  font-weight: 200;
}

.profile-pic {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  border: 2px;
}

.name {
  margin-left: 10px;
}

.username {
  margin-left: 10px;
}

.follow {
  margin: 0 0 0 auto;
  border: 0;
  border-radius: 10px;
}
<header>
  <img src="pic1.jpg" alt="Azraf Khan Zarif" >
  <div >Azraf Khan Zarif</div>
  <div >@Zarif</div>
  <button >Follow</button>
</header>

CodePudding user response:

when you put display: flex; it also add flex-direction: row; as default behavior of a flex.

because of which all your children inside <header> were rendered as a single row.

also adding margin: 0 0 0 auto to your follow button moves it to the right corner inside the whole flex row area. if you remove it you will see Follow button shows up just next to "@Zarif" text

enter image description here

CodePudding user response:

Because that’s how the Flexible Box Module works. Putting the display: flex instruction in the header element makes it a flexbox container, with the default values of flex-direction: row and justify-content: flex-start. This, in conjunction with margin: 0 0 0 auto, puts the button on the right.

Without flexbox, you could achieve the same result wth:

header {
    position: relative;
    ...
}

.follow {
    position: abolute;
    top: 0;
    right: 0;
    ...
}

Doing so, the button would be placed in the top-right corner because now it’d be positioned according to “parent coordinates”: the code would tell the button to move 0px away from the top, and 0px away from the right.

  •  Tags:  
  • Related