1

Is there a way to center element horizontally in page with margin auto but also to have 100px left and right if viewport gets smaller, so it would be like this together:

margin: 0 auto;
margin-left:100px;
margin-right:100px;

Or do I need to have parent container for this?

Ori Drori
  • 183,571
  • 29
  • 224
  • 209
Toniq
  • 4,492
  • 12
  • 50
  • 109
  • I would use a `@media` query. Test to see if the screen gets below a certain width and then change the margin. – disinfor Jan 08 '20 at 21:17
  • Does this answer your question? [Media Queries: How to target desktop, tablet and mobile?](https://stackoverflow.com/questions/6370690/media-queries-how-to-target-desktop-tablet-and-mobile) – disinfor Jan 08 '20 at 21:19

3 Answers3

1

the problem with auto is you can't even use it with calc(auto + 100px)

the most better and accurate way is to use flex

the justify-content property will center your element like margin: 0 auto; and you still have a room to play with margin

.parent{
    height: 200px;
    background: gray;
    display:flex;
    justify-content:center; /*center element*/ 
 
}

.child{
   height: 100px;
   width: 200px;
   background: yellow;
   margin: 0 100px; /*adding margin*/ 
}
<div class='parent'>
    <div class="child"></div>
</div>
Ayman Morsy
  • 1,279
  • 1
  • 10
  • 28
0

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>
agrm
  • 3,735
  • 4
  • 26
  • 36
-1

You could use padding for this