?原文網址:CSS--圖片鏈接居中展示的方法-CSDN博客
簡介
本文介紹CSS圖片鏈接水平居中展示的方法。
圖片鏈接
問題復現
源碼
<html xml:lang="cn" lang="cn"><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><meta name="keywords" content="anchor,fixed navigation hide anchor"><title></title>
</head><body><div class="container2"style="width: 400px ; height: 400px ; border: 3px solid black;"><a target="_blank" href="https://baidu.com"><img src=../img/bat.png alt="乒乓球拍"></a>
</div></body></html>
結果
方案1:img指定margin
給img元素添加margin,左右兩側自動,并指定display為block。
代碼
<html xml:lang="cn" lang="cn"><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><meta name="keywords" content="anchor,fixed navigation hide anchor"><title></title>
</head><body><div class="container2"style="width: 400px ; height: 400px ; border: 3px solid black;"><a target="_blank" href="https://baidu.com"><img src=../img/bat.png style="margin: 0 auto; display: block" alt="乒乓球拍"></a>
</div></body></html>
結果
方案2:父元素指定text-align
將父元素設置為:text-align: center
代碼
<html xml:lang="cn" lang="cn"><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><meta name="keywords" content="anchor,fixed navigation hide anchor"><title></title>
</head><body><div class="container2"style="width: 400px ; height: 400px ; text-align: center; border: 3px solid black;"><a target="_blank" href="https://baidu.com"><img src=../img/bat.png alt="乒乓球拍"></a>
</div></body></html>
結果
方案3:img絕對定位
代碼
<html xml:lang="cn" lang="cn"><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><meta name="keywords" content="anchor,fixed navigation hide anchor"><title></title>
</head><body><div class="container2" style="width: 400px; height: 400px; border: 3px solid black; position: relative;"><a target="_blank" href="https://baidu.com"><img src="../img/bat.png" alt="乒乓球拍" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);"></a>
</div></body></html>
結果
元素背景圖
問題復現
代碼
<html xml:lang="cn" lang="cn"><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><meta name="keywords" content="anchor,fixed navigation hide anchor"><title></title>
</head><body><div class="container1"style="width: 400px ; height: 400px ; border: 3px solid black;
background-image: url(../img/bat.png); background-repeat:no-repeat;"></div></body></html>
結果
解決方案
添加CSS:background-position:center center;
代碼
<html xml:lang="cn" lang="cn"><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><meta name="keywords" content="anchor,fixed navigation hide anchor"><title></title><style>body {/*display: flex;*/}</style>
</head><body><div class="container1"style="width: 400px ; height: 400px ; text-align: center; border: 3px solid black;
background-image: url(../img/bat.png); background-repeat:no-repeat;background-position:center center;"></div></body></html>
結果