為什么我的代碼沒有實現盒子居中呢?
<!DOCTYPE html>
<html>
<head>
? ? <meta charset="UTF-8">
? ? <title>已知寬高實現盒子水平垂直居中</title>
? ? <style type="text/css">
? ? .box {
? ? ? ? border: 1px solid #00ee00;
? ? ? ? height: 300px;
? ? ? ? width:300px;
? ? ? ? <!--父元素設置相對定位-->
? ? ? ? position:relative;
? ? }
? ? .box1 {
? ? ? ? ?<!--子元素設置絕對定位-->
? ? ? ? position:absolute;
? ? ? ? ?<!--子元素設置上和左偏移的值都為50%,是元素的左上角在父元素中心點的位置-->
? ? ? ? top:50%;
? ? ? ? left:50%;
? ? ? ? ?width: 100px;
? ? ? ? height: 100px;
? ? ? ? <!--margin-top和margin-left都設置為自身寬高的一半-->
? ? ? ? margin:-50px 0 0 -50px;
? ? ? ?
? ? ? ? border: 1px solid red;
? ? ? ?
? ? ? ??
? ? }
? ? </style>
</head>
<body>
? ? <div class="box">
? ? ? ? <div class="box1">box1</div>
? ? </div>
</body>
</html>
2021-01-21
首先注釋有點問題,
<!DOCTYPE?html> <html> <head> ????<meta?charset="UTF-8"> ????<title>已知寬高實現盒子水平垂直居中</title> ????<style?type="text/css"> ????????.box?{ ????????????border:?1px?solid?#00ee00; ????????????height:?300px; ????????????width:300px; ????????????position:relative; ????????????margin:?0?auto; ????????} ????????.box1?{ ????????????position:absolute; ????????????top:50%; ????????????left:50%; ????????????width:?100px; ????????????height:?100px; ????????????margin:-50px?0?0?-50px; ????????????border:?1px?solid?red; ????????} ????</style> </head> <body> <div?class="box"> ????<div?class="box1">box1</div> </div> </body> </html>2021-01-04
注釋用的不對吧,應該用/**? **/