在Ghost主题中居中图片

3
我在Ghost上使用免费的Starter主题,试图使图像居中但比段落和主要元素(60rem)更宽。
以下是保持图像位置的主要CSS元素,当我将img中的max-width更改为150%时,我可以让图像达到全宽度(我使用1100像素宽的图像),但这种方式不是居中的,它会向右浮动。
我为此制作了粗略的jsfiddle-https://jsfiddle.net/zbsa7ech/
img {
display: inline-block;
max-width: 100%;
min-height: 0;
height: auto;
vertical-align: middle;
border-radius: 5px;
}

我成功实现所需的结果的唯一方法是将max-width设置为200%,并且设置margin-left: -254px。

有没有简单的解决方案可以将图像居中放置在容器中,而不需要使用负边距左侧呢?

2个回答

2

您可以从“main”元素中删除宽度约束,仅将其应用于段落,使img不受限制。

CSS:

body {
    margin: 0;
    color: #283037;
    font-family: "Source Sans Pro", sans-serif;
    font-size: 1.8rem;
    font-weight: 400;
    line-height: 1.6;
}


.container {
    box-sizing: border-box;
    position: relative;
    width: 100%;
    max-width: 112rem;
    margin: 0 auto;
    padding: 0 2rem;
}


.site-main {
    width: 100%;

    margin: 0 auto;
}
.wrapper {
    max-width: 60rem;
    margin: 0 auto;
}


img {
    display: block;
    max-width: 100%;
    min-height: 0;
    height: auto;
    vertical-align: middle;
    border-radius: 5px;
    margin: 0 auto;
}

HTML:

<body>
<div class="container">

<header class="site-header"></header>

<main class="site-main wow fadeIn">

<p class='wrapper'>The Southern Railway (SR) gave the designation Sub to the wide variety of electric multiple units that were used on inner-suburban workings in the South London area. Originally these units were formed as three-car units, but in the 1940s, all surviving units were increased to four cars by the addition of an 'Augmentation' trailer. New four-car units were also built at this time, and these survived in passenger use until late 1983, by which time British Rail had allocated to them TOPS Class 405.</p>

<p><img src="https://i.sli.mg/DZAkY8.jpg" alt=""></p>

<p class='wrapper'>The Southern Railway (SR) gave the designation Sub to the wide variety of electric multiple units that were used on inner-suburban workings in the South London area. Originally these units were formed as three-car units, but in the 1940s, all surviving units were increased to four cars by the addition of an 'Augmentation' trailer. New four-car units were also built at this time, and these survived in passenger use until late 1983, by which time British Rail had allocated to them TOPS Class 405.</p>

</main>
</div>
</body>

代码笔:http://codepen.io/mwilkins91/pen/vyoeGg?editors=1100


0

您可以像这样将类添加到段落标记中 fiddle

<p class="img-container"><img src="https://i.sli.mg/DZAkY8.jpg" alt=""></p>

CSS

.img-container{
 display:flex;
 justify-content:center;
}

img {
 display: inline-block;
 max-width: 200%;
 min-height: 0;
 height: auto;
 vertical-align: middle;
 border-radius: 5px;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接