简体   繁体   中英

Display div at center horizontally and vertically at mobile device using CSS only

The task is to display block at center horizontally and vertically inside other block. I use this code

<div class="parent">
    <div class="child"></div>
</div>
.parent {
  background-color: #AFAFAF;
  bottom: 0;
  left: 0;
  position: absolute;
  right: 0;
  top: 0;
  width: 100%;
} 

.child {
  background-color: #FF0000;
  bottom: 0;
  height: 200px;
  left: 0;
  margin: auto;
  position: fixed;
  right: 0;
  top: 0;
  width: 200px;
}

and it works great on browsers and iOS devices, but this is the case in mobile android devices (not tablet): the inner div gets pinned to the top left corner, but when I inspect element using Adobe Edge Inspect I see that highlighted area for this inner div is displayed correctly. How can I fix this issue with centering on Android mobile? The size of inner block will change so the desigion should be universal.

I used to align div horizontally and verticaly the way you're doing but it seems like this technique is not really cross browser. Instead I took a look at the way Facebook was doing.

The demo on JsFiddle

The HTML :

<table>
    <tr>
        <td><div class="square">Some text</div></td>
    </tr>
</table>

The CSS :

html, body {
    height: 100%; 
    width: 100%; 
}

table {
    margin: 0px auto;
    height: 100%;
}

.square {
    width: 150px; 
    height: 150px; 
    background-color: red; 
}

NOTE : I recently took a look and it seems like Facebook changed the way they do it. They are still using table display properties but no more the table, tr and td tag (div instead).

The easiest way with your markup is {left:50%;margin-left:-100px;} .

Then the same with height. {top:50%;margin-top:-100px;}

In summary:

.child {
  background-color: #FF0000;
  height: 200px;
  left: 50%;
  position: fixed;
  top: 50%;
  width: 200px;
  margin: -100px 0 0 -100px;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM