Centralize div container materialize

Asked

Viewed 10,173 times

2

I got the following shit on mine HTML:

<div class="image">
    <div class="container center-align">
        <h1 class="grey-text text-lighten-5">Análise de Sistemas</h1>
        <span><b class="grey-text text-lighten-5">Tutoriais, Dicas, Tecnologia</b></span>
    </div>
</div>

The CSS class image:

.image {
    background-image: url("../images/vingadores.jpg");
    min-height: 400px;
    overflow: hidden;
    align-content: center;
    margin-bottom: 15px;
}

As image below the <div class="container center-align"> is not centered, I would like it to be in the middle of the image that is the div <div class="image">.

inserir a descrição da imagem aqui

Does anyone have any idea how I can do that?

I’ve looked here at Stack and Q&A about centering div didn’t help me.

OBS: I’m using the Framework Materialize.

1 answer

5


There are several ways to center both horizontally and vertically a div. In this case as we do not even know the values height nor the value width of any class container or center-align we can use a trick that will perfectly align this div without needing to know its values width or height.

This is how this can be achieved:

.center-align {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

Doing this, now the <div class="image"> will not be obeying parent div and will simply step out of the class .image and obey the body instead. So we need to make her obey the class .image to make the text obey this class so that it stays within it and is not going outside it. Then we will give a position:relative; for her:

.image {
    background-image: url("../images/vingadores.jpg");
    min-height: 400px;
    overflow: hidden;
    text-align:center; /* Adicionalmente iremos mudar esta linha que antigamente era align-content: center; para podermos alinhar o texto ao centro */
    position: relative;
}

Here’s an example below:

.center-align {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    
    /* código abaixo não relevante, só para o estilo! */
    color: #fff;
    background:#000;
    padding: 0 20px 10px 20px;
}
.image {
    min-height: 400px;
    overflow: hidden;
    text-align:center;
    position: relative;
    
    /* código abaixo não relevante, só para o estilo! */
    background: url(http://i.ytimg.com/vi/zeroxkAEKyM/maxresdefault.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
<div class="image">
    <div class="container center-align">
        <h1 class="grey-text text-lighten-5">Análise de Sistemas</h1>
        <span><b class="grey-text text-lighten-5">Tutoriais, Dicas, Tecnologia</b></span>
    </div>
</div>

  • 1

    Very good!! Thank you!!

Browser other questions tagged

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