Center element on a page

Asked

Viewed 92 times

1

I have a page and login to develop and there’s a logo right in the center of the page. Okay, I centered it this way:

bg{
    background-image: url("../imagens/bg.jpg");
    background-repeat: no-repeat;
    background-position: center;
    width: 100%;
    height: 1138px;
}
   .logo {
    background-image: url("../imagens/logo.png");
    width: 140px;
    height: 101px;
    margin-left: -70px;
    left: 50%;
    position: absolute;
}

I put a position:absolute and I would like to know if there is another way, because otherwise everything that comes under that div .logo I’ll have to put position and I don’t want that.

HTML:

<div class="bg">        
<div class="logo"></div>
</div>

Demonstrative image: inserir a descrição da imagem aqui

  • edited the question

  • Does none of these techniques (http://answall.com/questions/5225/centralizar-imagem-dentro-de-umadiv) solve the problem?

  • What I need is a little different this time. I can centralize and work the rest of the site perfectly, only I would prefer not to use position, because I have to keep on defining top of each element.

1 answer

3


Without touching the Markup and without touching the CSS, you just need to change the position:absolute; to the position:relative; in the element with the class .logo.

Absolute position: Jsfiddle

Problema com elemento ao centro via "position:absolute"

Resolved with relative position: Jsfiddle

Elemento ao centro via "position:relative"

Effectively the solution is to keep the element in its place in relation to the document flow, which allows the following elements to position themselves after the space occupied by your element .logo. See this answer for full information on position in CSS.

With absolute positioning you are removing the normal flow element from the document which forces you to change the Markup or to position absolutely all other elements.


bg{
    background-image: url("../imagens/bg.jpg");
    background-repeat: no-repeat;
    background-position: center;
    width: 100%;
    height: 1138px;
}
.logo {
    background-color:red;
    width: 140px;
    height: 101px;
    margin-left: -70px;
    left: 50%;
    position: relative;
}
<div class="bg">        
    <div class="logo"></div>
    <form>FORM</form>
</div>

  • Perfect answer, that’s exactly what I needed. I thought by default, the div was position:relative.

  • 1

    By default is static why is the top and left not "work" without setting at least position:relative.

Browser other questions tagged

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