Home > Enterprise >  How do I cut off the child element visibility by its parent container's shape?
How do I cut off the child element visibility by its parent container's shape?

Time:09-15

I want to add some text on a webpage, which will show up on the right edge of a container.

The only way I can think of is to fake the color of the text as the background color of the outsider container. But this implementation is quite risky as the outside background can be of different colors or even images on it.

How do I cut off the part that is outside of the parent container in CSS?

.container {
  margin: 2em;
  position: relative;
  width: 400px;
  height: 200px;
  background: #f1f1f1
}

.ads {
  position: absolute;
  right: 0;
  width: 5px;
  text-align: center;
  top: 50%;
  background: black;
  /* color: white; */
  transform: translateY(-50%);
  transition: 1s
}

.ads b {
  pointer-events: none;
  width: 100px;
  display: block
}

.ads:hover {
  width: 100px;
}

.high-level-container {
  margin: 2em;
  width: 500px;
  height: 600px;
  background: yellow;
}
<h3> The hack works </h3>

<div >
  <div >
    <b>Some Ads</b>
  </div>
</div>

<h3> The hack fails </h3>

<div >
  <div >
    <div >
      <b>Some Ads</b>
    </div>
  </div>
</div>

CodePudding user response:

If you want hide the rest text, you can use overflow:hidden;.

.container{overflow:hidden;}

But if you need wordbreak, use :

b{word-break: break-all;}

.container {
  margin: 2em;
  position: relative;
  width: 400px;
  height: 200px;
  background: #f1f1f1
}

.ads {
  position: absolute;
  right: 0;
  width: 5px;
  text-align: center;
  top: 50%;
  background: black;
  /* color: white; */
  transform: translateY(-50%);
  transition: 1s;
  overflow:hidden; <-- This one
}

.ads b {
  pointer-events: none;
  width: 100px;
  display: block
}

.ads:hover {
  width: 100px;
}

.high-level-container {
  margin: 2em;
  width: 500px;
  height: 600px;
  background: yellow;
}
<h3> The hack works </h3>

<div >
  <div >
    <b>Some Ads</b>
  </div>
</div>

<h3> The hack fails </h3>

<div >
  <div >
    <div >
      <b>Some Ads</b>
    </div>
  </div>
</div>

  • Related