【问题标题】:How to place image inside of a parent div properly如何正确地将图像放置在父 div 中
【发布时间】:2022-01-22 18:21:52
【问题描述】:

我有一个这样的 div:

<div class="p-5 mb-3 mainInfo">
           <div class="circle"><img src="https://nanoclub.ir/images/cut.png"></div>
</div>

结果是这样的:

但是,它应该像这样在 div 中显示:

这是 CSS:

    .mainInfo{
        background-color: #fff;
        border: .01rem round #e0e1ed;
        border-radius: 20px;
        color: #585CA1;
        height:50px;
    }
    .circle {
        position:absolute;
        width:150px;
        height:170px;
        border-radius:50%;
        background:#fff;
        right:100px;
        top:40%;
        transform:translateY(-50%);
    }

那么我怎样才能像预期的图像一样正确地将图像放置在circle div 中?

【问题讨论】:

  • 你只定位了圆,还需要将img定位在圆的div里面。

标签: html css twitter-bootstrap twitter-bootstrap-3


【解决方案1】:

我通过absolute 定位和::before 选择器实现了这一点。我还为图像添加了最大宽度的边框半径。

HTML:

<div class="mainInfo">
  <div class="circle">
    <img src="https://picsum.photos/200" />
  </div>
</div>

CSS:

.mainInfo{
  background-color: #fff;
  border: .01rem round #e0e1ed;
  border-radius: 20px;
  color: #585CA1;
  width:100%;
  height:5em;
  box-shadow: 0px 0px 17px -5px rgba(0,0,0,0.75);
  margin-top: 3em;
  display: flex;
  align-items: center;
  justify-content: center;
}

.circle {
  position: relative;
  width: 8em;
  height: 8em;
  background: #fff;
  border-radius: 50%;
  box-shadow: 0px 0px 17px -5px rgba(0,0,0,0.65);
}

.circle:before{
    position: absolute;
    content: "";
    width: 15em;
    height: 5em;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: #fff;
}

.circle img {
  position: absolute;
  max-width: 85%;
  border-radius: 50%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 200;
}

Link to the Demo

【讨论】:

  • 嗨,谢谢您的回答,但是如何在左侧和右侧添加文本?如果你能回答我,我真的很感激,我真的需要这个......
  • 很高兴为您提供帮助。您可以再次使用绝对定位或将 .mainInfo justify-content 属性更改为 space-between 然后对圆使用绝对居中。
猜你喜欢
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-20
  • 2021-04-04
  • 1970-01-01
  • 2014-01-10
相关资源
最近更新 更多