问题描述:

I have a list in an angular-app where each item can either contain a small image (as a div's background -> red) and some text or only text.

li {

display: flex;

border: 1px solid black;

width: 80%;

margin-bottom: 5%;

list-style: none;

position: relative;

}

.text {

text-align: center;

width: 100%;

background: lightgrey;

}

.image {

background: red;

width: 25%;

height: 100%;

position: absolute;

}

<ul>

<li><div class="text"><p>item 1<br/>some text</p></div>

</li>

<li><div class="image"></div><div class="text split"><p>item 2<br/>some text</p></div>

</li>

<li><div class="image"></div><div class="text split"><p>item 2<br/>some more text in a very very long line which may break at the end</p></div>

</li>

</ul>

网友答案:

I hope you needed something like this:

li {
  display: flex;
  border: 1px solid black;
  background: lightgrey;
  width: 80%;
  margin-bottom: 5%;
  list-style: none;
  position: relative;
}

.text {
  text-align: center;
  width: 100%;
  position: relative;
  z-index: 2;
}

.image {
  background: red;
  width: 25%;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  z-index: 1;
}
.more {
   width: 60%;
}
<ul>
  <li><div class="text"><p>item 1<br/>some text</p></div>
  </li>
  <li><div class="image"></div><div class="text split"><p>item 2<br/>some text</p></div>
  </li>
  <li><div class="image more"></div><div class="text split"><p>item 3<br/>some text</p></div>
  </li>
</ul>
网友答案:

Just always add the container to the right and use the + sibling selector.

HTML:

<li>
    <div class="image"></div>
    <div class="text split">
        <p>item 2<br/>some text</p>
    </div>
    <div></div>
</li>

CSS:

.image + .text {
    width: 50%
}

.image + .text + div {
    width: 25%
}
网友答案:

Another way to do this is to use absolute positioning and transform, as below:

  <div class="wrapper">
    <div class="image">
    </div>
    <div class="text">
      THIS IS CENTERED TEXT
    </div>
  </div>

  <div class="wrapper">
    <div class="text">
      THIS IS CENTERED TEXT
    </div>
  </div>

and the css:

.wrapper {
  height: 100px;
  width: 300px;
  margin: 0 auto;
  margin-top: 10px;
  border: 2px solid black;
  position: relative;
}

.text {
  position: absolute;
  text-align: center;
  top: 50%;
  left: 50%;
  transform: translateX(-50%)translateY(-50%);
}

.image {
  height: 100px;
  width: 100px;
  background: red;
}

The advantage of this is that it does not rely on setting widths, so the text is ALWAYS centered both horizontally and vertically - regardless of text or image size.

jsfiddle here.

相关阅读:
Top