Doubts about CSS and positioning

Asked

Viewed 71 times

1

Let’s say I’ll position a div 100px of height and width, (a square) then I position this square in margin-left 40% and margin-top 20%, the square is more or less centered, right? Now I will put a text written "hi" inside it with the tag <p>, now if I use the magnifying glass, the following happens, only the right side and the bottom part of the square will expand while its other two sides do not expand and the text remains intact, let’s say I want everything to expand without the sides moving as it would do this ?

About the code I mentioned above:

.caracteristicas{
  position: absolute;
  background-color: green;
  height: 100px;
  width: 100px;
  margin-left: 40%;
  margin-top: 20%;
}
<html>
  <head>
    <title>Aprendendo a centralizar</title>
    <link rel="stylesheet" type="text/css" href="style.css">
  </head>
  <body>
    <div class="caracteristicas">
      <p>oi</p>
    </div>
  </body>
</html>

  • Just a tip, stop while it’s time to use theposition: absolute. Try to center things using the position: relative that will have better results. But, if you combine the absolute at the margin, in one way or another is not collaborating to structure work. Whenever use absolute match the attribute left, top, right, bottom. Something like top: 20% for example.

  • In your example, to make the element 100% centered, resizing the browser or applying the magnifying glass, remove the position, change margin-left: 40%, margin-top: 20% for margin: 20% auto 0 auto. This ensures 100% centering of the object.

1 answer

1


Nowadays there are some more responsive techniques to centralize a div on the screen, is the case of the grids system.

How it works

Basically the idea of the css grids system, copies the idea of <tables>, where you work with rows and columns.

The code

I made a simple code, in which the centralized div is centralized corresponding to her container, which is 100% the screen size and centered horizontally by margin and vertically by vertical-align.

An example running:

html, body{
  width: 100%;
  height: 100%;
  margin: 0;
  display: table;
}
.container_centralizado{
  vertical-align: middle;
  display: table-cell;
  position: relative;
}
.centralizado{
  width: 200px;
  height: 50px;
  vertical-align: middle;
  margin: 0 auto;
}

/** Aqui para baixo é só para fins de estilização, favor ignorar **/

.centralizado{
  color: white;
  background: blue;
}
.centralizado span{
  width: 100%;
  line-height: 3em;
  display: block;
  text-align: center;
  font-family: arial;
}
<div class="container_centralizado">
  <div class="centralizado">
    <span>Div Centralizada</span>
  </div>
</div>

PS: It’s always interesting to use the meta tag viewport in your html. So, from this example, when using the "magnifying glass", the div is always centralized, expanding centrally.

Browser other questions tagged

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