You can use border-left
and border-right
to add a border to the element's left and right hand side. Make sure you set the border color to transparent
and add background-clip: padding-box
to make sure the border is truly invisible:
.centered {
margin: 0 auto;
width: 100px;
height: 100px;
background: blue;
background-clip: padding-box;
border-left: 100px solid transparent;
border-right: 100px solid transparent;
}
<div class="centered"></div>
Another approach is to use a parent element with padding:
.parent {
padding: 0 100px;
}
.centered {
margin: 0 auto;
width: 100px;
height: 100px;
background: blue;
}
<div class="parent">
<div class="centered"></div>
</div>
Depending on your use case you might be able to use the <body>
as the parent, saving you from adding an otherwise superfluous parent element:
body {
padding: 0 100px;
}
.centered {
margin: 0 auto;
width: 100px;
height: 100px;
background: blue;
}
<div class="centered"></div>