If the horizontal centering of a box (DIV) can be done relatively easily with the “margin: 0 auto;” property, vertically it is a little more delicate, but not overly difficult. We will display one of the multiple methods.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
.div_centr_ext { display:block; position: relative; border:1px solid darkgray; width:300px; min-height:200px; margin:5px; padding:5px; box-shadow: 10px 10px 10px rgba(0, 0, 0, .4); border-radius:10px; margin:0 auto; } .div_centr_int { margin: 0; position: absolute; top: 50%; left: 50%; -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); width:90%; height: auto; font-size:1.2em; border:1px dashed lightgray; } @media only screen and (max-width: 600px) { .div_centr_ext { display:block; width:100%; margin:0px; padding:0px; } } |
.div_centr_ext
can have width:max-content; if contextual adjustment is desired; however, a min-width
property could also be inserted.
If we are only interested in vertically centered alignment, we can consider, at .div_centr_int
, instead of:
1 2 3 |
left: 50%; -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); |
to use:
1 2 3 |
top: 50%; -ms-transform: translateY(-50%); transform: translateY(-50%); |
1 2 3 4 5 6 |
<div class="div_centr_ext"> <h2>Test</h2> <div class="div_centr_int"> I am vertically and horizontally centered. </div> </div> |