<!DOCTYPE HTML> | |
<html> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"> | |
<title>div定位</title> | |
<style> | |
/*方法1*/ | |
body > .d { | |
background-color: green; | |
width: 500px; | |
height: 100px; | |
position: relative; | |
} | |
.bar { | |
background-color: red; | |
width: 200px; | |
height: 50px; | |
margin: auto; | |
position: absolute; | |
top: 0; | |
bottom: 0; | |
right: 0; | |
} | |
/*方法2*/ | |
body>.d2{ | |
background-color: green; | |
width: 500px; | |
height: 100px; | |
display:table-cell; /*此元素会作为一个表格单元格显示(类似 <td> 和 <th>)*/ | |
vertical-align:middle; | |
text-align: right; | |
} | |
.bar2{ | |
width:200px; | |
height:50px; | |
display:inline-block; | |
background-color: red; | |
/*float:right;*/ | |
} | |
/*方法3*/ | |
body>.d3{ | |
background-color: green; | |
width: 500px; | |
height: 100px; | |
display:flex; | |
justify-content: flex-end; | |
align-items:center; | |
} | |
.bar3{ | |
width:200px; | |
height:50px; | |
background-color: red; | |
} | |
/*方法4*/ | |
body>.d4{ | |
background-color: green; | |
width: 500px; | |
height: 100px; | |
position: relative; | |
} | |
.bar4{ | |
width:200px; | |
height:50px; | |
background-color: red; | |
margin:auto; | |
position:absolute; /*设定水平和垂直偏移父元素的50%,再根据实际长度将子元素上左挪回一半大小*/ | |
left: 100%; | |
top:50%; | |
margin-left: -200px; | |
margin-top:-25px; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="d"> | |
<div class="bar"> | |
</div> | |
</div> | |
<hr> | |
<div class="d2"> | |
<div class="bar2"></div> | |
</div> | |
<hr> | |
<div class="d3"> | |
<div class="bar3"></div> | |
</div> | |
<hr> | |
<div class="d4"> | |
<div class="bar4"></div> | |
</div> | |
</body> | |
</html> |
2
最新推荐文章于 2022-07-19 18:43:40 发布