Home >Web Front-end >HTML Tutorial >div horizontally centered vertically centered_html/css_WEB-ITnose
Horizontally centered
Option 1:
Use margin:0 auto
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>test</title><style type="text/css"> body{margin:0;padding: 10px;} .wrap{width: 600px;height: 400px;position: absolute;border:1px solid #333;} .box{position: relative;margin:0 auto;width:300px;height:150px;background-color: #999;text-align: center;}</style></head><body> <div class="wrap"> <div class="box">hello</div> </div></body></html>
Option 2:
Use:
left:50%;top:50%;margin-left:-width/2;margin-top:-height/2;
After positioning halfway, Then move the negative margin left and up. Achieve horizontal and vertical centering effects
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>test</title><style type="text/css"> body{margin:0;padding: 10px;} .wrap{width: 600px;height: 400px;position: absolute;border:1px solid #333;} .box{position: absolute;left:50%;top:50%;margin-left:-150px;margin-top:-75px;width:300px;height:150px;background-color: #999;text-align: center;}</style></head><body> <div class="wrap"> <div class="box">hello</div> </div></body></html>
tip: If you want to center vertically, simple settings like margin: auto auto will not work..