Get child element to respect parent element Width

2019-03-03 11:09发布

问题:

I was working on a wepage earlier this week where the 'banner-image' was being cut off the view-port of the screen depending on the browser and size of screen.

I thought that by simply converting the Parent Container to 'Height: 100vh' this would make all child elements fit within the parent container that is now set to fit the height of any viewport.

This did not work as I intended it to. The banner image was still being cutoff even though the parent container was set to 100vh.

Is there a way to do this?

JSFiddle Link

CSS

.parent {
    width: 100%;
    background-color: blue;
   border: 1px dashed blue;
    text-align: center;
}

.child-header {
    background-color: rgba(122, 234, 221, .4);
    width: 100%;
    background-color: gray;
    position: relative;
}

p {
    color: white;
    font-family: sans-serif;
    text-align: center;
}

h1 {
    color: white;
    text-align: center;
    font-family: sans-serif;
}

.banner-image {
    background-color: black;
    width: 80%;
    min-height: 500px;
    position: relative;
    margin: 0 auto;
}

HTML

<div class="parent"><!-- Wrapper Parent Container -->

    <div class="child-header">
        <p>Cool header with a nav will go here</p>
    </div>

    <h1>Some Headline Tag Here</h1>

    <div class="banner-image">
    </div>

    <h2>Blah Blah Blah...</h2>


</div><!-- End Wrapper -->

回答1:

I thought that by simply converting the Parent Container to 'Height: 100vh' this would make all child elements fit within the parent container that is now set to fit the height of any viewport.

100vh is not a magic number that makes all other elements fit into the viewport window.

If you want your banner image to be related to the height of the viewport, set a height either in percentage or, since you are already using then, viewport units.

* {
  margin: 0;
  padding: 0;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
.parent {
  background-color: blue;
  border: 1px dashed blue;
  text-align: center;
  min-height: 100vh;
}
.child-header {
  background-color: rgba(122, 234, 221, .4);
  background-color: gray;
  position: relative;
}
p {
  color: white;
  font-family: sans-serif;
  text-align: center;
}
h1 {
  color: white;
  text-align: center;
  font-family: sans-serif;
}
.banner-image {
  background-color: black;
  width: 80%;
  min-height: 50vh;
  position: relative;
  margin: 0 auto;
}
<div class="parent">
  <!-- Wrapper Parent Container -->
  <div class="child-header">
    <p>Cool header with a nav will go here</p>
  </div>
  <h1>Some Headline Tag Here</h1>

  <div class="banner-image"></div>
  <h2>Blah Blah Blah...</h2>

</div>

Jsfiddle Demo

Alternative layout methods might suit you better such as flexbox or calculating element dimensions using calc...it all depends on what it is you are trying to do.