浏览器默认从左往右渲染元素,在没有超出父容器的宽度的前提下 如果子容器的宽度能够被容纳 设置margin-right是没有用的
解释
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.box-wrapper {
display: flex;
width: 500px;
height: 500px;
background-color: orange;
/* overflow: hidden; */
}
.box{
width: 200px;
height: 200px;
margin: 0 auto;
/*当父元素水平空间不足,设置右外边距失效,优先保证左外边距*/
margin-right: -300px;
}
.box-1{
background-color: pink;
}
</style>
</head>
<body>
<div class="box-wrapper">
<div class="box box-1"></div>
</div>
<script type="text/javascript">
</script>
</body>
</html>
不生效
生效
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.box-wrapper {
display: flex;
width: 500px;
height: 500px;
background-color: orange;
/* overflow: hidden; */
}
.box{
width: 200px;
height: 200px;
margin: 0 auto;
/*当父元素水平空间不足,设置右外边距失效,优先保证左外边距*/
margin: 0 200px;
}
.box-1{
background-color: pink;
}
</style>
</head>
<body>
<div class="box-wrapper">
<div class="box box-1"></div>
</div>
<script type="text/javascript">
</script>
</body>
</html>
解决办法在元素外面再套一层div,display设置flex
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.box-wrapper {
display: flex;
width: 500px;
height: 500px;
background-color: orange;
/* overflow: hidden; */
}
.box{
width: 200px;
height: 200px;
margin: 0 auto;
/*当父元素水平空间不足,设置右外边距失效,优先保证左外边距*/
margin-right: -200px;
}
.box-1{
background-color: pink;
}
</style>
</head>
<body>
<div class="box-wrapper">
<div class="box box-1"></div>
</div>
<script type="text/javascript">
</script>
</body>
</html>