Centered vertical line causing width is issues

Viewed 44

I have been able to create a centered vertical line but it increases my webpage width off of my screen! I would like some insight on how I can create a centered vertical line down my page while keeping page width to fit my screen (so that there is no horizontal scroll bar).

When I have removed the line my page width is perfect therefore I do not think it is one of my divs causing the problem.

body {
  background-color: lightblue
}

.vertical_line {
  border-left: 6px solid black;
  height: 500px;
  position: relative;
  left: 50%;
  margin-left: auto;
  z-index: -1;
}

.section-2 {
  width: 100%;
  height: 200px;
}

.section-3 {
  position: relative;
  top: 50;
  width: 500px;
  height: 60%;
  padding: 20px;
  margin-left: auto;
  margin-right: auto;
  background-color: green;
}
<section class="section-2">
  <div class="topnav">
    <a style="background-color:grey; width:100px">this is my nav bar</a>
  </div>
  <div class="vertical_line"></div>
</section>

<section class="section-3">
  <div class="paragraph"></div>
</section>

<div class="vertical_line"></div>

1 Answers

Problem arises because you used position: relative; and shifted it 50% left, but it means element is still part of flow and shifting it pushes it past the edge of the screen. On the other hand position absolute removes it from the flow. But if you want to use position: relative; for some reason, then add overflow-x : hidden; in the body, it will work fine in your case. Also a good CSS reset always helps, so as you do not get unexpected scrollbars.

* {
  padding: 0px;
  margin: 0px;
}

body {
  background-color: lightblue;
  width: 100%;
  min-height: 100vh;
}

.vertical_line {
  border-left: 6px solid black;
  height: 500px;
  position: absolute;
  left: 50%;
  margin-left: auto;
  z-index: -1;
}

.section-2 {
  width: 100%;
  height: 200px;
}

.section-3 {
  position: relative;
  top: 50;
  width: 500px;
  height: 60%;
  padding: 20px;
  margin-left: auto;
  margin-right: auto;
  background-color: green;
}
<html>

<section class="section-2">
  <div class="topnav">
    <a style="background-color:grey; width:100px">this is my nav bar</a>
  </div>

  <div class="vertical_line"></div>

</section>


<section class="section-3">
  <div class="paragraph"></div>
</section>

<div class="vertical_line"></div>

</html>

With help of overflow-x: hidden; and position : relative; :

 * {
   padding: 0px;
   margin: 0px;

 }

 body {
   width: 100%;
   min-height: 100vh;
   overflow-x: hidden;
 }

 .vl {
   border-left: 6px solid black;
   height: 5000px;
   position: relative;
   left: 50%;
 }
  <html>

    <body>
      <h2>Vertical Line</h2>
      <div class="vl"></div>
    </body>

  </html>

Related