简体   繁体   中英

How to insert an external HTML in a div by CSS?

I'm trying insert an external HTML template in a <div> by CSS but I can't. Firstly I tried with content , but I got no results.

.overbox {
    display: none;
    position: absolute;     
    background-color: #FFFFFF;
    content: url("../mytemplate.html");     
    padding: 10px;
    top: 25%;
    left: 25%;
    width: auto;
    height: auto;
    z-index:1002;
    overflow: auto; 
}

Any ideas? Maybe with jQuery or Javascript?

CSS is meant for adding presentation to the page , and not content . Therefore I feel that you should use JavaScript if you want to dynamically generate content . CSS is not opt for this.

Reference: Link

Does the content of the external template change depending on a users actions (ie an tick box is clicked or an option selected)?

Does the template need to be loaded multiple times into the same div (ie every few minutes or every time a button is clicked)?

If the answer to either of these questions is yes then you should be using ajax. Something along the lines of the following would work:

$.ajax({
  url: '../mytemplate.html',
  success:function(data){
    $('.overbox').html(data);
  }
});

Please note that this is simplified and should also error check etc. For more info see the jquery docs on ajax or ' The Perfect jQuery AJAX Request '.

If the answer to both the above questions is no then you should be using a server side language to include the file in the div before it is sent to the client.

An example of this using PHP would be:

<div class="overbox">
  <?php include '../mytemplate.html';?>
</div>

The primary purpose of using the content in css is to insert static data :before and :after pseudo-elements, what you trying to do is the task most suited for javascript. In content you can use url just to specify images but cannot render the complete html content.

I think that with javascript, jquery is the best way. Try this function

   function addDiv() {
    var div = document.createElement('div');
    div.className = 'row';
     div.innerHTML = '<input type="text" name="name" value="" />\
    <input type="text" name="value" value="" />\ 
    <input type="button" value="-" onclick="tempfunction()">';
     document.getElementById('content').appendChild(div);
   }

I'm not sure why you have opted for this method, but content CSS property only works with Pseudo elements before and after . Your CSS code should be some thing like this.

.overbox:before{
content: url(../mytemplate.html);
position: absolute;     
background-color: #FFFFFF;
padding: 10px;
top: 25%;
left: 25%;
width: auto;
height: auto;
z-index:1002;
overflow: auto; 
 }

Note: you can't use external link in content property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM