0

I have a div called #text, inside another div #box. Right now I've tried to center #text by doing this:

#box {
  width: 50%;
  #text {position: relative; margin-left: 48%;}
}

This code puts #text approximately in the center of #box, but when I resize the screen, the size of #text changes relative to the size of the screen, so the size of its margin-right changes, and it is no longer exactly in the center.

I've heard there is a "hack" for this involving a few wrapper divs, but I don't want to overcomplicate my css or html. Is there a simple way to horizontally position a div exactly in the center of its parent?

doelleri
  • 19,232
  • 5
  • 61
  • 65
Jeff Caros
  • 919
  • 5
  • 12
  • 32

4 Answers4

1

Using flexbox is IMO the best way to center child horizontaly and verticaly. Its support is good.

Albert221
  • 5,223
  • 5
  • 25
  • 41
1

First off the CSS you posted is not valid. You can accomplish what you are looking for with something like this:

CSS

body {
    width:100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
#box {
    width:100%;
    height: 500px;
    background: lightblue
}
#test {
    width: 300px;
    height: 300px;
    border: 1px solid red;
    margin: 0 auto
}

HTML

<div id="box">
    <div id="test">
        hello
    </div>
</div>

See the JS.Fiddle

crazymatt
  • 3,266
  • 1
  • 25
  • 41
1

use margin: 0 auto; in the css of #text

waipa mark
  • 46
  • 3
1

You want exact center of page, regardless of content? Do something like this:

p {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

Relative to the parent, set the following attribute on the container for your element:

div.containerOfPs {
  position: relative;
}
Josh Burgess
  • 9,327
  • 33
  • 46