0

I have div block which contains form as the following:

<div class="divClass">
    <form id="frm" method="post" action="/NotDefinedYet/index.xhtml" class="frmClass">
        <input type="text" name="j_idt9:j_idt10:Username" placeholder="Username">
    </form>
</div>

corresponding css-stylesheet

.divClass{
    width: 350px;
    height: 450px;
}
.frmClass{
    position: relative;        
    margin:auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 280px;
    height: 150px;
}

Eventually i have only horizontl centering form relative to div block. But I need to centering both vertical and horizontal. How it can be implemented?

4 Answers4

0

Try this: (fiddle)

.divClass{
    position: relative;
    width: 350px;
    height: 450px;
}
.frmClass{
    position: absolute;        
    top: 50%;
    left: 50%;
    margin-top: -75px;
    margin-left: -140px;
    width: 280px;
    height: 150px;
}

It works because:

  1. An absolute component inside a relative container is layed out relatively to the container, therefore specifying top as 50% will place the component's top position at the middle of the container;
  2. Given we know the height of the component, once we specify margin-top as -half that height, the component will be exactly at the center of the container.

Same is applied to horizontally center the component.

Ben Barkay
  • 5,473
  • 2
  • 20
  • 29
0
.divClass{
    width: 350px;
    height: 450px;
    text-align:center;
}
.frmClass{
    position: relative;        
    margin:0 auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 280px;
    height: 150px;
    vertical-align: middle;
    top: 50%;
}

And see this link http://jsfiddle.net/bipin_kumar/DmMVd/2/

Bipin Kumar Pal
  • 1,009
  • 2
  • 8
  • 16
0

My favourite way if you don't need legacy browser support. I like it because it is independent of parent and child container sizes.

http://jsfiddle.net/samih/K4kLj/

.divClass{
    position: relative;
    background-color: grey;
    width: 350px;
    height: 450px;
}
.frmClass{
    width: 280px;
    height: 150px;
    position: absolute;
    top: 50%;
   left: 50%;
    -webkit-transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    background-color: white;
}

Works in IE9+, chrome and firefox. See http://caniuse.com/#search=transform for a full list of browser support.

Samih
  • 1,078
  • 9
  • 15
-2

place the form inside center tag.

div

center

form

form will be aligned in the middle inside the div

premgowda
  • 31
  • 3