Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

html - Why body doesn't hide overflow?

What I want: Set the body width smaller than viewport and then hide everything outside the body.
(I know I can use a div container and get what I want)

Here is a very simple example (Codepen) :

body {
  overflow-x: hidden;
  margin: 0 auto;
}

.hidden {
  position: relative;
  left: -50px;
}


/*----- Decoration -----*/
body {
  border: 5px solid red;
  height: 2000px;
  width: 1000px;
}

.hidden {
  display: flex;
  align-items: center;
  text-align: center;
  height: 100px;
  width: 100px;
  background-color: green;
}

body::after {
  content: "Container";
  position: absolute;
  left: 50%;
  top: 50%;
}
/*-----------------------*/
<div class="hidden" >Should be hidden</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use clip-path to do that. You can just add

clip-path: inset(0 0 0 0);

to your body. You can see a working snippet below:

body {
  margin: 0 auto;
  clip-path: inset(0 0 0 0);
}

.hidden {
  position: relative;
  left: -50px;
}


/*----- Decoration -----*/
body {
  border: 5px solid red;
  height: 2000px;
  width: 80%;
}

.hidden {
  display: flex;
  align-items: center;
  text-align: center;
  height: 100px;
  width: 100px;
  background-color: green;
}

body::after {
  content: "Container";
  position: absolute;
  left: 50%;
  top: 50%;
}
/*-----------------------*/
<div class="hidden" >Should be hidden</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...