[英]Variable size image with max width/height inside a fitted centered element
我有一個<a>
標記,里面有一個<img>
,我想在屏幕上垂直和水平放置,但也要有一個max-height和max-width,以便在屏幕周圍很好地放置空白。 它需要適用於任何屏幕尺寸的縱向和橫向圖像,並且根本無法裁剪圖像。 但是,我無法獲得圖像的最大高度。
<a>
也有一些位於圖像左側下方的文本,因此,我試圖使<a>
的大小與<img>
的大小匹配,以使此文本的位置正確。
HTML:
<a href="#">
<img src="image.jpg" alt="it's a picture">
<p>Image Title</p>
</a>
CSS:
a {
display: block;
position: relative;
top: 50%;
transform: translateY(-50%);
margin: 0 auto;
max-width: 60%;
max-height: 60%;
}
img {
max-width: 100%;
max-height: 100%;
}
p {
position: relative;
top: 10px;
}
當未指定寬度時,設置百分比最大寬度與設置常規百分比寬度幾乎相同,因此我將鏈接大小更改為簡單寬度/高度60%,希望可以。 現在,最簡單的居中方法是Flexbox。 您可以在此處了解更多信息:
http://philipwalton.github.io/solved-by-flexbox/demos/vertical-centering/
我必須添加一個額外的div來包裝圖像和字幕,以便文本可以與圖像的左下方對齊。
<a>
<div>
<img src="image.jpg"/>
<span>asd</span>
</div>
</a>
這是flexbox CSS:
body {
display: flex;
align-items: center;
justify-content: center;
}
a {
display: block;
width: 60%;
height: 60%;
border:2px solid red;
display: flex;
align-items: center;
justify-content: center;
}
a span {
display:block;
}
a div {
max-width:100%;
max-height:100%;
display:block;
margin:0 auto;
}
a img {
max-width:100%;
max-height:100%;
display:block;
}
這是這樣的:
也適用於人像圖像:
來自CSS-Tricks的這段代碼將使您幾乎可以將圖像居中放置在屏幕中間:
<a href="#">
<img src="/pathTo/image.jpg" alt="it's a picture">
<span class="title">The Image's Title</span>
</a>
a {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.title {
position:fixed;
width:327px;
text-align:center;
}
訣竅是在<a>
元素上使用固定位置,以便同時考慮頂部和左側CSS屬性。 隨着視口變小,圖像將不會調整大小,並且將保持在橫向/縱向布局的中心。 假設圖像的高度和寬度是已知的(在這種情況下,圖像為327px x 327px-我不確定“可變尺寸圖像”到底是什么意思) .title
與圖像的寬度相等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.