How can I vertical allign content to be responsive using @media rule?

118 views Asked by At

I am trying to copy the style of this site http://www.shouldigoout.com/ which has some text ( h1 p a ) centrally alligned vertically and horizontally on the page.

The page use the @media rule to adjust the sizing for different display sizes.

How can I simply achieve this effect using css?

The site seems to use javascript/jquery to position the elements on the page is that the only way to achieve this effect?

2

There are 2 answers

1
Vandervals On

The example is using javascript but you can do it using flexbox:

@media(min-width: 1000px){    
    .parent{
      display: flex;
      flex-flow: row wrap;
      align-items: center;
    }
}

Flexbox is the easiest way to do this and the @media allows you to select the interval of window size that you want the rule to be active. In this case, it will be centered if the window is wider than 1000px.

0
Knut Holm On

CodePen example

If you are using SASS (and Bourbon) you can do something like this:

@mixin center($xy:xy) {
  @if $xy == xy {
    left: 50%;
    top: 50%;
    bottom: auto;
    right: auto;
    @include transform(translateX(-50%) translateY(-50%));
  }
  @else if $xy == x {
    left: 50%;
    right: auto;
    @include transform(translateX(-50%));
  }
  @else if $xy == y {
    top: 50%;
    bottom: auto;
    @include transform(translateY(-50%));
  }
}

h1 {
  position: absolute;
  display: block;
  @include center;
}

Compiled CSS + HTML:

 h1 {
  position: absolute;
  display: block;
  left: 50%;
  top: 50%;
  bottom: auto;
  right: auto;
  -webkit-transform: translateX(-50%) translateY(-50%);
  -moz-transform: translateX(-50%) translateY(-50%);
  -ms-transform: translateX(-50%) translateY(-50%);
  -o-transform: translateX(-50%) translateY(-50%);
  transform: translateX(-50%) translateY(-50%);
}
<h1>This is a test</h1>