【问题标题】:Centered image and Text to the left pushing image居中的图像和文本向左推图像
【发布时间】:2015-06-04 01:16:31
【问题描述】:

我想让图像居中并在其左侧放置文本。我尝试过的所有内容要么将文本放在图像下方,图像上方,要么将图像推向右侧,我输入的越多。谁能帮我?我是 html 和 css 的新手。

body {
  margin: 0;
  padding: 0;
}
h1 {
  text-align: center;
  border: solid;
  background-color: #FF0000;
}
span {
  display: inline-block;
  border: dashed blue;
  color: #ff0000;
  float: left;
}
.mainPicture {
  display: block;
  width: 30%;
  margin-left: auto;
  margin-right: auto;
}
<!DOCTYPE html>
<html>

<head>
  <link type="text/css" rel="stylesheet" href=main.css>
</head>

<body>
  <h1>Welcome</h1>
  <div>
    <span>  My name is asd asd. I am currently attending  </span>
    <img src="onlinePicture.jpg" alt="Picture of Me" class="mainPicture">
  </div>
</body>

</html>

【问题讨论】:

  • 的宽度设置为:40%。这将使您的屏幕看起来像:40%span|30%img|40%margin

标签: html css spacing


【解决方案1】:

使用 CSS 定位应该会对您有所帮助。

设置div为position: relative;,然后设置图片为position: absolute;。然后偏移图像left: 50%; 并通过使用margin-left: -15%; 删除一半来抵消图像的宽度。

例子:

body {
  margin: 0;
  padding: 0;
}
h1 {
  text-align: center;
  border: solid;
  background-color: #FF0000;
}
div {
  position: relative;
}
span {
  display: inline-block;
  border: dashed blue;
  color: #ff0000;
  float: left;
}
.mainPicture {
  display: block;
  width: 30%;
  position: absolute;
  left: 50%;
  margin-left: -15%;
}
<!DOCTYPE html>
<html>

<head>
  <link type="text/css" rel="stylesheet" href=main.css>
</head>

<body>
  <h1>Welcome</h1>
  <div>
    <span>  My name is asd asd. I am currently attending  </span>
    <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150" alt="Picture of Me" class="mainPicture">
  </div>
</body>

</html>

【讨论】:

    【解决方案2】:

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }
    
    h1 {
        text-align: center;
        border: solid;
        background-color: #FF0000;
    }
    div {
        /*text-align: center;*/
        font-size: 0;
        margin: 10px auto;
    }
    div > span {
        display: inline-block;
        vertical-align: top;
        border: 1px dashed blue;
        color: #ff0000;
        font-size: 16px;
        width: 35%;
        text-align: center;
    }
    div > span:nth-child(2) {
        width: 30%;
        border: none;
    }
    div > span:nth-child(2) img{    
         background: #ccc;
         width: 100%;    
    }
    <h1>Welcome</h1>
    <div> 
    <span>  My name is asd asd. I am currently attending</span>
    <span><img src="http://mc-fc.net/wp-content/uploads/2012/11/124124124_mcfc.gif" alt="Picture of Me" class="mainPicture" /></span> 
    </div>

    【讨论】:

      猜你喜欢
      • 2015-03-03
      • 1970-01-01
      • 2012-06-12
      • 1970-01-01
      • 1970-01-01
      • 2015-01-05
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      相关资源
      最近更新 更多