【问题标题】:Make left and right margins equal when outer component is not known当外部组件未知时,使左右边距相等
【发布时间】:2016-04-21 14:09:40
【问题描述】:

我想将以下图片居中显示:

我有以下样式项目:

var itemStyle = {
  display: 'block',
  width: this.computeWidth(),
  height: '250px',
  backgroundImage: 'url(' + imageLocation + ')',
  backgroundPosition: 'center !important',
  backgroundSize: 'cover',
  boxShadow: '10px 10px 5px #888888',
  borderRadius: '15px',
  marginLeft: 'auto !important',
  marginRight: 'auto !important'
};

我是这样显示的:

<div style={itemStyle}>
</div>

this.computeWidth()就是这个方法,我根据页面调整图片的宽度:

  computeWidth: function() {
    console.log("this.state.window.width: " + this.state.window.width);
    if(this.state.window.width > 350) {
      return '250px';
    }
    return Math.floor(0.7 * this.state.window.width).toString() + 'px';
  },

我也尝试使用这种方法计算marginLeftmarginRight

  computeMargin: function() {
      if(this.state.window.width > 350) {
        return 'margin-auto';
      }
      return Math.floor(0.15 * this.state.window.width).toString() + 'px';
  },

但是,图像没有再次居中。

那么如何确保图像位于页面的中心?(最好不要更改包含它的组件的css

【问题讨论】:

  • 您是定位元素还是背景-图像,不清楚。居中元素有 数以千计 个您可以检查的相关问题。
  • backgroundImage。但这是一样的,不是吗?因为背景图片占据了整个元素。

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


【解决方案1】:

margin: Xpx auto 有什么问题?它应该可以工作,因为图像定义了宽度。或者,您可以将 flexbox 属性添加到父级以使子级居中:

.parent {
  display: inline-flex;
  justify-content: center;
  width: 100%;
}

【讨论】:

    【解决方案2】:

    CSS 应该足以解决这个问题。将图像包裹在 div 中,并使用 margin 属性将其居中。

    <div class="img-wrap">
         <img src="foo.jpg">
    </div>
    

    .img-wrap { margin: 0 auto; }
    

    更多详情请参阅此处:CSS-Tricks centering guide


    编辑 - 对于居中的背景图像,将以下 CSS 应用于 div:

    background-image: url("foo.jpg");
    background-position: 50% 50%;
    background-repeat: no-repeat;
    background-size: contain;    /* Full image in div, no cropping, preserve aspect ratio */
    

    这通过将图像的中心沿 div 中的两个轴(x 和 y)移动到一半来使图像居中。因此,完美的居中。


    或者,将其用于英雄图像:

    background-size: cover;      /* Fill div (even if img is cropped), preserve aspect ratio */
    

    更多关于背景居中的信息:Sitepoint: background-position property

    【讨论】:

    • 我需要将图像保留为背景。
    猜你喜欢
    • 2016-10-21
    • 2022-01-26
    • 2016-12-07
    • 2021-12-24
    • 1970-01-01
    • 2016-09-29
    • 1970-01-01
    • 2021-12-23
    • 2020-09-22
    相关资源
    最近更新 更多