Margin does not push content to the center

Asked

Viewed 66 times

-1

I recently asked a question because my margin top did not push my div down, following the example in the previous question I was able to solve, but now, using the same explanation of the previous question I cannot center my content.

.side-menu-user-infos {
  background: #FFF;
  display: block;
  height: 190px;
  border-bottom: 1px solid rgb(155, 158, 162);
  position: relative;
}

.side-menu-user-photo {  
  border-radius: 50%;
  width: 30%;
  height: 80px;
  margin: 30px auto 0 auto;
  position: relative;
  box-shadow: 1px 1px 7px;
}

img {
  width: 100%;
  height: 100%;
}

.side-menu-user-name {
  color: #374147;
  margin: 15px auto 0 auto;
}
<div class="side-menu-user-infos">
    <div class="side-menu-user-photo">
        <img src="" alt="">
    </div>

    <div class="side-menu-user-name">
        Fernando Munhoz
    </div>
</div>

How are you getting:

inserir a descrição da imagem aqui

How it should look:

inserir a descrição da imagem aqui

Why my text in the "side-menu-user-name" class does not align in the center and in the "side-menu-user-photo" class I use the margin in the same way and the content centralizes??

  • 1

    Please do not remove the edit that adds the snippet executable. It is recommended for snippets of code that can be executed on the client side (such as HTML and CSS).

1 answer

3


The class element side-menu-user-photo has a width (width) defined differently from site-menu-user-name, which does not have a width explicitly defined in your CSS, which makes it 100% wide. So margin: 0 auto Centralize the element relative to the X axis, it must have a width previously specified in the CSS.

If you pay attention, through developer tools, you may realize that because it is an element block level (display: block by default, since it is a div), the width is 100% by default. Thus, the element will not be centered, because it already occupies the total size on the X axis:

Exemplificação em imagem do parágrafo anterior.

As you can see above, the element is centered yes! In reality, what is not centralized is the text. So, if you don’t want to set a specific width for the site-menu-user-name, just use the text-align: center, which will align the text relative to the X axis:

.side-menu-user-name {
  color: #374147;
  margin: 15px auto 0 auto;
  text-align: center;
}

In short, when using the margin: 0 auto to center an element, keep in mind that it will only work if that element has a defined width, which is not the case for the class element site-menu-user-name.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.