0

I have an app on reactjs, when i add margin to the text it adds margin to the div and main div shifts down. JSX Code:

import React, {Component} from 'react';
import './Travel.css';
class Travel extends Component {
    render(){
            return(
                <div className='top'>
                    <div className='content'>
                        <span className='conth'>
                            <h1>A TRAVELS</h1>
                            <h1>YEARBOOK</h1>
                        </span>
                    </div>
                </div>
            );
    }
}
export default Travel;


CSS Code:
@import url(//fonts.googleapis.com/css?family=Open+Sans:800);
.top{
    height:789px;
    width: 100%;
    background-image: url('travel.jpg');
    background-repeat: no-repeat;
    background-size: cover;
    z-index: -1;
}
.content h1{
    margin-top: 10px;
}
.conth{
    font-family: 'Open Sans';
    font-size: 43px;
    width: 500px;
    color: #ffffff;
}

Please help me how to solve this problem.

1 Answers1

1

The effect you've fallen victim to is called collapsing margins. Here's a very simplified example:

body {
  min-height: 100vh;
  min-width: 100vw;
}

.outside {
  background-color: red;
  height: 300px;
  margin-top: 0;
  width: 400px;
}

.inside {
  background-color: orange;
  margin-top: 200px;
  height: 50%;
}
<body>
  <div class="outside">
    <div class="inside"></div>
  </div>
</body>

To prevent this, simply add a minimal padding-top to .outer:

body {
  min-height: 100vh;
  min-width: 100vw;
}

.outside {
  background-color: red;
  height: 300px;
  margin-top: 0;
  padding-top: 1px;
  width: 400px;
}

.inside {
  background-color: orange;
  margin-top: 200px;
  height: 50%;
}
<body>
  <div class="outside">
    <div class="inside"></div>
  </div>
</body>

CSS Tricks has a decent article on this:

https://css-tricks.com/what-you-should-know-about-collapsing-margins/

connexo
  • 53,704
  • 14
  • 91
  • 128