I have two divs, one inside another and the inner div has ap tag which has aligned middle. markup is
<div class="box1">
<div class="box2">
<p>hello</p>
</div>
</div>
style rules are
.box1 {
width: 400px;
height: 400px;
background: red;
text-align: center;
}
.box2 {
display: table-cell;
width: 200px;
height: 200px;
margin: auto;
vertical-align: middle;
text-align: center;
background: yellow;
}
What i am trying to do is centering the p tag vertically and horizontally inside the inner div(box2) and centering the inner div vertically and horizontall insde the outer div (box1). i failed to center the inner div(box2) inside the outer div. Please help me to do it. i have created a fiddle for this -> http://jsfiddle.net/64WAW/1/
Please look at this:
http://jsfiddle.net/itz2k13/64WAW/2/
.box1 {
display: table-cell;
width: 400px;
height: 400px;
background: red;
text-align: center;
vertical-align: middle;
}
.box2 {
width: 200px;
height: 200px;
background: yellow;
margin: auto;
line-height: 200px;
}
HTML:
<div class="box1">
<div class="box2container">
<div class="box2">
<p>hello</p>
</div>
</div>
</div>
Css:
.box1 {
width: 400px;
height: 400px;
background: red;
text-align: center;
}
.box2 {
position:relative;
top:-50%;
left:-50%;
width: 200px;
height: 200px;
background: yellow;
line-height:200px;
}
.box2container{
width: 200px;
height: 200px;
position:relative;
top:50%;
left:50%;
}
This solution avoid using display:table-cell
which is not supported by older browsers. Check out the fiddle
you will use flexbox, it is easy.it is like this:
.box1,
.box2{
display: -moz-box; /*Safari, iOS, Android browser, older WebKit browsers. */
display: -webkit-box;/* Firefox (buggy) */
display: -ms-flexbox; /*IE 10*/
display: -webkit-flex;/*Chrome 21+ */
display: flex;/*Opera 12.1, Firefox 22+ */
-webkit-box-align: center;
-moz-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
-webkit-box-pack: center;
-moz-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
}
.box1{
width: 400px;
height: 400px;
background: red;
text-align: center;
}
.box2 {
background: yellow;
width: 200px;
height: 200px;
}
use the display:inline-block and add :after for it parent container:
.box1 {
width: 400px;
height: 400px;
background: red;
text-align: center;
}
.box2 {
display: inline-block;
width: 200px;
height: 200px;
vertical-align: middle;
text-align: center;
background: yellow;
}
.box1:after {
content:"";
width: 1px;
height: 100%;
position: relative;
display: inline-block;
vertical-align: middle;
}
the demo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.